search

Home  >  Q&A  >  body text

python简单的问题,智商不够用了。。。

为何遍历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

PHPzPHPz2873 days ago529

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师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

    reply
    0
  • 黄舟

    黄舟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[:]

    reply
    0
  • Cancelreply