python嵌套列表和循环逻辑错误

时间:2018-08-28 18:44:26

标签: python-3.x list nested-lists

我正在尝试一次练习python一个主题。今天,我正在学习列表和嵌套列表,其中包含更多列表和元组。我尝试在嵌套列表中玩,但是程序没有执行我想要的操作

逻辑错误:应该打印可乐而不是幻想

代码:

# creating a list of products in a vending machine
products = [(1,"fanta"),(2,"coke")]

# user input
choice = input("What do you want: ")

# creates a variable 'item' that is assigned to each item in list 'products'
for item in products:
    # creates two variables for each 'item' 
    item_number, product = (item)
    if choice == "fanta" or choice == str(1):
        # deletes the item because it was chosen
        del products[0]
        # why is product fanta and not coke since fanta is deleted?
        print(product, "are still left in the machine")

2 个答案:

答案 0 :(得分:0)

一种可能的解决方案是创建一个没有子列表的新列表。

请参考以下程序,您可以轻松地进行列表理解并根据输入值的类型进行操作。

# creating a list of products in a vending machine
products = [(1,"fanta"),(2,"coke")]

# user input
choice = input("What do you want: ")

if choice.isdigit():
    print([x for x in products if int(choice) != x[0]])
else:
    print([x for x in products if choice != x[1]])

输出:

What do you want: 1
[(1, 'fanta'), (2, 'coke')]


What do you want: 1
[(2, 'coke')]

What do you want: 2
[(1, 'fanta')]

What do you want: fanta
[(2, 'coke')]

What do you want: coke
[(1, 'fanta')]

答案 1 :(得分:0)

由于products是列表,因此您可以通过列表理解来打印其余项目:

print(', '.join([product[1] for product in products]), "are still left in the machine")

将打印列表中所有剩余的项目:

coke are still left in the machine

如果您只想删除用户输入的items,则不需要遍历products列表,则可以安全地删除以下行:

for item in products: # remove this line

然后,如果您向products添加更多项目,例如:

products = [(1,"fanta"),(2,"coke"),(3,"mt. dew")]

在删除用户选择后,列表理解将仅打印其余项目:

What do you want: 1    
coke, mt. dew are still left in the machine

What do you want: fanta
coke, mt. dew are still left in the machine