Skip to main content
 首页 » 编程设计

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

2025年05月04日14oomusou

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