首页 > 解决方案 > list.remove(x): x 不在使用 while 循环的列表中

问题描述

场景

使用sandwich_orders练习 7-8 中的列表,确保三明治pastrami至少出现在列表中 3 次。在程序开头附近添加代码以打印一条消息,说明熟食店已用完pastrami,然后使用 while 循环删除所有出现的pastramifrom sandwich_orders。确保没有pastrami三明治最终进入finished_sandwiches

我写的代码

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}")

以下是执行代码后的错误

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**

标签: python

解决方案


如果您已经弹出最后一个“熏牛肉”三明治,它不再在列表中,lst.pop

请注意,您不会更改 current_sandwich,因此它也是一个无限循环

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

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}")

推荐阅读