首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >list.remove(x):x没有在列表中使用while循环

list.remove(x):x没有在列表中使用while循环
EN

Stack Overflow用户
提问于 2019-12-19 17:12:24
回答 1查看 154关注 0票数 0

场景

使用练习7-8中的列表sandwich_orders,确保三明治pastrami至少在列表中出现三次。在程序开始附近添加代码,打印一条消息,说明deli已经用完pastrami,然后使用while循环从sandwich_orders中删除所有出现的pastrami。确保没有pastrami三明治在finished_sandwiches结束。

代码我编写了

代码语言:javascript
复制
sandwich_orders=['egg&mayo','cheese&onion','chicken&sweetcorn','pastrami','pastrami',
'egg&watercress','pastrami','pastrami']
finished_sandwiches=[ ]

current_sandwich=sandwich_orders.pop()

print(f"\nYour Sandwich has been prepared : {current_sandwich}")

while current_sandwich:

    print(f"\nCurrent sandwich is {current_sandwich}!!")

    if current_sandwich=='pastrami':
        sandwich_orders.remove('pastrami')
        print(f"\n{current_sandwich} has been removed from the orders")
    else:
        finished_sandwiches.append(current_sandwich)
        print(f"\nYour Sandwich has been prepared : {current_sandwich}")
print(f"\nList of finshed swandwiches : {finished_sandwiches}")

print(f"\nList of Sandwich Orders recieved : {sandwich_orders}")

下面的是执行代码后的错误

代码语言:javascript
复制
Traceback (most recent call last):
  File "C:\Users\thota01\AppData\Local\Programs\Python\Python38\Python_Input_whileLoops\movietickets.py", line 9, in <module>
    sandwich_orders.remove('pastrami')

**ValueError: list.remove(x): x not in list**
EN

回答 1

Stack Overflow用户

发布于 2019-12-19 17:23:01

如果你已经打开了最后一个‘意大利面’三明治,它就不在名单上了,lst.pop

请注意,您没有更改current_sandwich anywere,所以它也是一个infinate循环

顺便说一句,while current_sandwich会让你得到异常,因为你会弹出一个空列表

代码语言:javascript
复制
sandwich_orders=['egg&mayo','cheese&onion','chicken&sweetcorn','pastrami','pastrami',
'egg&watercress','pastrami','pastrami']
finished_sandwiches=[ ]

print(f"\nYour Sandwich has been prepared : {current_sandwich}")
while sandwich_orders:
    current_sandwich = sandwich_orders.pop()
    print(f"\nCurrent sandwich is {current_sandwich}!!")
    if current_sandwich=='pastrami':
        print(f"\n{current_sandwich} has been removed from the orders")
    else:
        finished_sandwiches.append(current_sandwich)
        print(f"\nYour Sandwich has been prepared : {current_sandwich}")
print(f"\nList of finshed swandwiches : {finished_sandwiches}")

print(f"\nList of Sandwich Orders recieved : {sandwich_orders}")
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59414172

复制
相关文章

相似问题

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