为什么删除for循环中的列表项不能正常工作?

2024-04-25 07:59:44 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么不从列表中删除每个0?你知道吗

list = [0,0,5,3,0,8,0,4] 

for num in list:
    if num == 0:
        list.remove(0)

print(list)

Tags: in列表forifnumremovelistprint
1条回答
网友
1楼 · 发布于 2024-04-25 07:59:44

因为你在循环的时候改变了列表,这几乎总是个坏主意。下面演示一下发生了什么:

list = [0,0,5,3,0,8,0,4] 

for num in list:
    print(num, list)
    if num == 0:
        list.remove(0)

print(list)

Output

0 [0, 0, 5, 3, 0, 8, 0, 4]
5 [0, 5, 3, 0, 8, 0, 4]
3 [0, 5, 3, 0, 8, 0, 4]
0 [0, 5, 3, 0, 8, 0, 4]
0 [5, 3, 0, 8, 0, 4]
[5, 3, 8, 0, 4]

这是文件中的相关部分,它告诉我们这是个坏主意:

Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, e.g. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

for x in a[:]:
    if x < 0: a.remove(x)

Source

您可以使用非常简单的列表理解来实现这一点:

list_ = [0,0,5,3,0,8,0,4]  # list shadows the built-in name, don't use it
list_ = [num for num in list_ if num != 0]
print(list_)

Output:

[5, 3, 8, 4]

相关问题 更多 >