繁体   English   中英

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

[英]list.remove(x): x not in list using while loop

场景

使用列表sandwich_orders练习7-8,确保三明治pastrami出现在列表中至少三次。 在程序开头附近添加代码以打印一条消息,说明熟食店的pastrami已用完,然后使用 while 循环从sandwich_orders pastrami删除所有出现的pastrami 确保没有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了最后一个“ lst.pop ”三明治, lst.pop不再在列表中了, 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}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM