python tricks

A pitfall that may be encountered when removing an element from a list in a for loop in python

example:

nums = [1, 2, 3, 4, 5]
for i in nums:
    if i == 3:
        nums.remove(i)
    print(i)

# result:
# 1
# 2
# 3
# 5
# Solution:
temp = []
nums = [1, 2, 3, 4, 5]
for i in nums:
    if not i == 3:
        temp.append(i)

nums = temp
for i in nums:
    print(i)

猜你喜欢

转载自blog.csdn.net/mihanglaoban/article/details/81628007