为何遍历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
天蓬老师2017-04-18 10:28:17
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
黄舟2017-04-18 10:28:17
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[:]