我有一个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)

最佳答案

在您评论下方的第一行

 other_recipients = email_to[sw]


您不是要复制该列表,而只是对其进行另一个引用。这意味着对remove的调用也会影响您的原始列表。如果您打算将other_recipients用作email_to[sw]的副本,则必须显式复制它

other_recipients = list(email_to[sw]) # or email_to[sw][:]




一个简单的例子演示了这种行为

>>> 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]


您可以使用is运算符来表明它们是同一对象

>>> a is b
True
>>> c = list(a)
>>> c is a
False

10-08 18:08