【问题标题】:how do i include a string or an 'and' inside a list?如何在列表中包含字符串或“和”?
【发布时间】:2020-04-06 05:42:06
【问题描述】:

所以在我的代码中我想做这个结构

将 、 、 和 混合在一起。

我有这个代码

import random

ingredient = ['flour', 'baking powder', 'butter', 'milk', 'eggs', 'vanilla', 'sugar']

def create_recipe(main_ingredient, baking, measure, ingredient):
    """Create a random recipe and print it."""
    m_ingredient = random.choice(main_ingredient) #random choice from the main ingredient
    baking_ = random.choice(baking) #random choice from the baking list
    ingredients = random.choice(ingredient) #random choice from the ingredient list

    print("***", m_ingredient.title(), baking_.title() , "Recipe ***")
    print("Ingredients:")
    print(random.randint(1,3), random.choice(measure), m_ingredient)
    for i in range(len(ingredients)): #get the random ingredients
        print(random.randint(1,3), random.choice(measure), ingredient[i])
    print ("Method:")

    selected=[] # this is where the ingredients from the recipe
    selected_items = "Mix the"
    for i in range(len(ingredients)):
        ingredients= str(random.choice(ingredient))
        selected.append(ingredients)
    selected.insert(-2,'and')
    print(selected_items,",".join(selected), "together.") 

我有这个作为它的输出。

将鸡蛋、发酵粉、糖和面粉、糖混合在一起。

如何在列表中的最后一项之前添加“和”并使其与我想要的结构一样?

【问题讨论】:

    标签: python-3.x list function


    【解决方案1】:

    将所有成分放入列表并根据您选择的字符串格式对其进行切片:

    things = ['flour', 'baking powder', 'butter', 'milk', 'eggs', 'vanilla', 'sugar']
    
    # join all but the last element using ", " as seperator, then print the last element
    # after the "and"    
    print(f"You need {', '.join(things[:-1])} and {things[-1]}")
    
    # or
    
    print("You need", ', '.join(things[:-1]), "and", things[-1])
    

    输出:

    You need flour, baking powder, butter, milk, eggs, vanilla and sugar
    

    更多资源:

    【讨论】:

    • 如果我有一个随机列表并且它给了我随机列表怎么办?我也应该这样做吗?
    • 你读过切片符号吗?该语句不关心您的 ist 中有多少东西,或者它是否是随机的——它只取最后一个元素之外的所有东西并加入它,放入“and”,然后是最后一个元素。烹饪注意事项:收据中通常有一个“好”的订单。 f.e.混合面粉、发酵粉和香草糖。在一个单独的碗中放入黄油和糖,在高速搅拌下混合,直到颜色从黄色变为白色和蓬松,混合干黄油和其他湿成分等 - 随机列表可能不会发生;o)跨度>
    • @prvlx 更多信息请参见cooking.stackexchange.com/questions/tagged/baking ;o)
    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 2017-07-04
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多