python - list.remove(x): x 不在使用 while 循环的列表中
问题描述
场景:
使用sandwich_orders
练习 7-8 中的列表,确保三明治pastrami
至少出现在列表中 3 次。在程序开头附近添加代码以打印一条消息,说明熟食店已用完pastrami
,然后使用 while 循环删除所有出现的pastrami
from 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**
解决方案
如果您已经弹出最后一个“熏牛肉”三明治,它不再在列表中,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}")
推荐阅读
- angular - Angular2:从 URL 访问查询参数给出错误
- csv - 如何加载包含多行记录的 CSV 文件?
- javascript - 显示和打开引导模式
- javascript - 标头中不包含授权标头
- angular - 单击Angular 5中其他组件的复选框时更新组件数据
- c# - 错误:输入字符串的格式不正确
- bash - 在函数内的直到语句处扩展“$@”
- php - 存储和公共之间的 Laravel Symlink 不起作用?
- android - 从 1.0.2 到 1.1.0 的约束布局库更新出错 (Guideline.getAnchor)
- magento - 已弃用:__autoload() 已弃用,在 magento cd 1.9 上使用 spl_autoload_register()