我有一个用于访问列表项的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)
答案 0 :(得分:5)
在评论下面的第一行
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
答案 1 :(得分:1)
for sw, contacts in email_to.items():
...
other_recipients = email_to[sw]
...
other_recipients.remove(receiver) # here you change your list
other_recipients.remove(receiverEmail)