为什么我的list.append不能永久添加我的项目?

时间:2018-07-14 10:47:58

标签: python python-3.x list

将项目添加到列表中后,下次添加其他项目时,该项目将被删除。

food_choice = str(input("Do you want to add an item, remove an item or  search for a recipes? "))
food = []
if food_choice in ["Add", "add"]:
    food_to_add = str(input("Which item would you like to add? "))
    food.append(food_to_add)
    print(food_to_add, "has been addded to your fridge list.")
    print(food)

1 个答案:

答案 0 :(得分:1)

您需要初始化列表,然后重复添加项目。实现此目的的自然方法是将您的逻辑包装在while循环中,并添加一个结束循环的选项,例如关键字“结束”。

否则,就像您的代码中一样,food = []每次都会初始化一个新的空列表。

food = []

while True:
    food_choice = str(input("Do you want to add, remove, search, or end? "))

    if food_choice.lower() == 'end':
        break

    if food_choice.lower() == 'add':
        food_to_add = str(input("Which item would you like to add? "))
        food.append(food_to_add)
        print(food_to_add, "has been addded to your fridge list.")
        print(food)

用法示例:

Do you want to add, remove, search, or end? add
Which item would you like to add? banana
banana has been addded to your fridge list.
['banana']
Do you want to add, remove, search, or end? add
Which item would you like to add? orange
orange has been addded to your fridge list.
['banana', 'orange']
Do you want to add, remove, search, or end? end