Как мне включить строку или 'и' внутри списка? - PullRequest
1 голос
/ 06 апреля 2020

Так что в моем коде я хочу сделать эту структуру

Смешать,,, и вместе.

У меня есть этот код

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.") 

У меня было это как выход для него.

Смешайте яйца, разрыхлитель, сахар и муку, сахар вместе.

Как добавить знак «и» перед последним элементом в списке и сделать его таким же, как структура, которую я хотел?

1 Ответ

0 голосов
/ 06 апреля 2020

Поместите все свои ингредиенты в список и нарежьте их в соответствии с выбранным форматированием строки:

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

Дополнительные ресурсы:

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...