python简单的问题,智商不够用了。。。
PHPz
PHPz 2017-04-18 10:26:17
0
2
495

为何遍历a只遍历3次?智商不够了,list里最后一个为何没遍历到?智商不够了。。。

a = ["asd_1","asd_2","3","4"]
b = a

for i in a:
    print(i)
    if i.find('asd_') < 0:
        b.remove(i)

输出:
asd_1
asd_2
3

PHPz
PHPz

学习是最好的投资!

reply all(2)
Peter_Zhu

Because of the mutable objects in the list, a and b actually only want the same address. Remove on b will affect the iteration of a. If you don’t believe me, print out a and see

a = ["asd_1", "asd_2", "3", "4"]
b = a

for i in a:
    print(i)
    if i.find('asd_') < 0:
        b.remove(i)
print a

Output:

asd_1
asd_2
3
['asd_1', 'asd_2', '4']

At this time, the length of a has become 3

黄舟

In the above code, b is just a reference to a. If you modify b, a will also be modified, which directly affects the iteration of a.

You can try it

b = a.copy()

or

b = a[:]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template