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

python nested lists and for loop logic error

我正在尝试一次练习 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")

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

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

# 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')]

由于 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