为什么我的列表在迭代时会跳过某些元素?

时间:2017-03-31 09:05:15

标签: python

我正在尝试编写一些代码,将一个列表中的元素添加到另一个列表中,然后将其从第一个列表中删除。它也不应该将重复项添加到if语句所在的新列表中。 但是,当添加到“个人”列表并从“sentence_list”列表中删除时,它会错过某些单词,例如“not”和“for”。这也不是随机的,每次都会错过相同的单词。有什么帮助吗?

<VirtualHost *:80>
    ProxyPass / http://localhost:8080/
    ProxyPassReverse / http://localhost:8080/

    <Location />
        AuthType Basic
        AuthBasicProvider file
        AuthName "Restricted Content"

        AuthUserFile "/path/to/userfile"
        AuthGroupFile "/path/to/groupfile"
        Require group users
        Require group admins

        RewriteEngine On

        RewriteCond %{LA-U:REMOTE_USER} (.+)
        RewriteRule . - [E=RU:%1,NS]
        RequestHeader set X-Forwarded-User %{RU}e

        RewriteCond %{???} (.+)
        RewriteRule . - [E=RG:%1,NS]
        RequestHeader set X-Forwarded-User-Groups %{RG}e

        RequestHeader unset Authorization
    </Location>
</VirtualHost>

2 个答案:

答案 0 :(得分:2)

问题是您要从正在循环的列表中删除项目。您可以通过复制列表并循环遍历它来解决此问题,如下所示:

sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
sentence_list = sentence.lower().split()
individuals = []

#We slice with [:] to make a copy of the list
orig_list = sentence_list[:]
for i in orig_list:
  if i in individuals:
    print ("yes")
    sentence_list.remove(i)
  else:
    individuals.append(i)
    sentence_list.remove(i)
    print ("individuals", individuals)
    print ("sentence_list", sentence_list)

列表现在是预期的:

print(individuals)
print(sentence_list)

['ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you']
[]

答案 1 :(得分:1)

通常,在遍历它时,不应向列表中添加或删除元素。鉴于您要删除列表中的每个元素,只需删除sentence_list.remove(i)行。

如果你真的需要从列表中删除一些你正在迭代的元素,我可以:创建一个新的空列表并添加你想要保留的元素,或者跟踪哪个迭代后要删除的列表中的索引,然后在循环后删除。

对于第一个解决方案,

oldList = [1, 2, 3, 4]
newList = []

for i in oldList:
    shouldRemove = i % 2
    if not shouldRemove:
        newList.append(i)

第二,

oldList = [1, 2, 3, 4]
indicesToKeep = []

for i, e in enumerate(oldList):
    shouldRemove = e % 2
    if not shouldRemove:
        indicesToKeep.append(i)

newList = [e for i, e in enumerate(oldList) if i in indicesToKeep]