循环遍历列表,使用 while vs if

时间:2021-04-21 13:26:28

标签: python for-loop if-statement

书中的示例问题

如果我想检查 pastrami 的列表并确保 finished 中没有熏牛肉,这可以正常工作:

orders = ['tuna sub', 'chicken parmasean', 'pastrami', 'chicken teryiaki', 'pastrami']
finished = []

for order in orders:
    while 'pastrami' in orders:
        orders.remove('pastrami')
    print("preparing " + order + " ...")
    finished.append(order)

for sandwich in finished:
    print(sandwich + " is ready")

└─$ python3 sandwiches.py
preparing tuna sub ...
preparing chicken parmasean ...
preparing chicken teryiaki ...
tuna sub is ready
chicken parmasean is ready
chicken teryiaki is ready
                           

但是使用 if 来检查 order 不起作用。

orders = ['tuna sub', 'chicken parmasean', 'pastrami', 'chicken teryiaki', 'pastrami']
finished = []

for order in orders:
    if order == 'pastrami':
        orders.remove('pastrami')
    print("preparing " + order + " ...")
    finished.append(order)

for sandwich in finished:
    print(sandwich + " is ready")


─$ python3 sandwiches.py
preparing tuna sub ...
preparing chicken parmasean ...
preparing pastrami ...
preparing pastrami ...
tuna sub is ready
chicken parmasean is ready
pastrami is ready
pastrami is ready

我不明白为什么会这样?

1 个答案:

答案 0 :(得分:0)

也许你想否定你的if

finished = []

for order in orders:
    if order != 'pastrami':
        print("preparing " + order + " ...")
        finished.append(order)