我正在尝试一次只练习一个主题的python。今天我学习了列表和嵌套列表,其中包含了更多的列表和元组。我尝试使用嵌套列表,但程序没有按我的要求运行
逻辑错误:应该打印coke而不是fanta
代码:
# 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")
发布于 2018-08-29 03:18:09
因为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
发布于 2018-08-29 03:10:39
一种可能的解决方案是创建一个没有子列表的新列表。
参考下面的程序,根据输入值的类型,你可以很容易地理解列表。
# 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')]
https://stackoverflow.com/questions/52064439
复制相似问题