Python while while循环不断缩短我的列表!为什么?

ste*_*eph 1 python while-loop

我有一个while循环,用于访问列表的项目.我从不[故意]改变列表的内容,但不知何故,这个列表在循环的每次迭代中都缩短了!我不知道为什么或发生这种情况.由于这种缩短,我的'列表索引'变得超出范围,因为列表不再是其原始大小.

为什么/这种缩短发生在哪里?

# email_to = { sw: [person1, email1, person2, email2, ..] }
for sw, contacts in email_to.items():
    number = len(contacts)
    number = number-1
    i = 0
    while i < number:
       print "All items in contacts: ", contacts  # <------- 'contacts' keeps getting shorter!!? WHY!?
       recipientName = contacts[i]
           if recipientName in contactsDict[sw]:
               print recipientName, "is a contact"
               affiliationType = "C"
           elif recipientName in developersDict[sw]:
               print recipientName, "is a developer"
           else:
               print recipientName, "is of unknown affiliation"
       recipientEmail = contacts[i+1]
       i += 2

       #If I remove this part below, the rest of the code works and the list is not altered ????
       other_recipients = email_to[sw]
       receiver = recipientName
       receiverIndex = other_recipients.index(receiver)
       receiverEmail = other_recipients[receiverIndex+1]
       if receiver in other_recipients:
           other_recipients.remove(receiver)
           other_recipients.remove(receiverEmail)
Run Code Online (Sandbox Code Playgroud)

Rya*_*ing 5

在评论下面的第一行

 other_recipients = email_to[sw]
Run Code Online (Sandbox Code Playgroud)

你没有复制那个列表,你只是另外引用它.这意味着调用remove也会影响您的原始列表.如果您打算other_recipients成为副本email_to[sw],则必须明确复制它

other_recipients = list(email_to[sw]) # or email_to[sw][:]
Run Code Online (Sandbox Code Playgroud)

一个快速示例演示了此行为

>>> a = [1,5,7]
>>> b = a
>>> b.append(99) #appends to b
>>> a # a now has 99 as well
[1, 5, 7, 99]
>>> a.remove(1) # removes from a
>>> b # b loses 1 as well
[5, 7, 99]
Run Code Online (Sandbox Code Playgroud)

您可以使用is运算符来显示它们是同一个对象

>>> a is b
True
>>> c = list(a)
>>> c is a
False
Run Code Online (Sandbox Code Playgroud)