首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python嵌套列表和for循环逻辑错误

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

Stack Overflow用户
提问于 2018-08-29 02:44:26
回答 2查看 88关注 0票数 1

我正在尝试一次只练习一个主题的python。今天我学习了列表和嵌套列表,其中包含了更多的列表和元组。我尝试使用嵌套列表,但程序没有按我的要求运行

逻辑错误:应该打印coke而不是fanta

代码:

代码语言:javascript
复制
# 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")
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-29 03:18:09

因为products是一个列表,所以您可以使用列表理解来打印剩余的项目:

代码语言:javascript
复制
print(', '.join([product[1] for product in products]), "are still left in the machine")

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

代码语言:javascript
复制
coke are still left in the machine

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

代码语言:javascript
复制
for item in products: # remove this line

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

代码语言:javascript
复制
products = [(1,"fanta"),(2,"coke"),(3,"mt. dew")]

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

代码语言:javascript
复制
What do you want: 1    
coke, mt. dew are still left in the machine

代码语言:javascript
复制
What do you want: fanta
coke, mt. dew are still left in the machine
票数 0
EN

Stack Overflow用户

发布于 2018-08-29 03:10:39

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

参考下面的程序,根据输入值的类型,你可以很容易地理解列表。

代码语言:javascript
复制
# 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]])

输出:

代码语言:javascript
复制
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')]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52064439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档