我正在尝试一次练习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")
由于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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句