Python不会从lis中删除项目

2024-09-27 07:22:17 发布

您现在位置:Python中文网/ 问答频道 /正文

filtered_list = ['PerezHilton', 'tomCruise', 'q', 'p']
#BIO[user]['follows'] is just a list of strings say ['a', 'b', 'katieh']
#specs is also a string say eg. 'katieh'
for user in filtered_list:
    if specs not in BIO[user]['follows']:
        filtered_list.remove(user)

对于某些原因,上述代码给出了此错误“ValueError:列表.删除(x) :x not in list”但很明显“p”在列表中,为什么它没有检测到“p”,但却找到了“q”??在

Im-soo被难住了,但任何帮助都是感激的,谢谢

**抱歉,我现在修好了*


Tags: in列表isnotfilteredlistbiojust
2条回答

在这篇文章的底部,列出了一行中正确完成这一点的清单。以下是对这个问题的一些见解。在

不要做这样的事情:

for item in list_:
    list_.remove(item)

因为糟糕和混乱的事情发生了。在

^{pr2}$

每次删除项时,都会更改其余项的索引,这会使循环混乱。在遍历列表时,从列表中删除项的一个好方法是按索引执行,并向后工作,这样删除操作不会影响其余的迭代。这是更好的,因为如果删除第9个元素,那么第8个元素仍然是第8个元素,但是第10个元素将成为第9个元素。如果您已经处理过这个元素,那么您不关心它的索引是什么。在

>>> list_ = range(10)
>>> for i in xrange(len(list_) - 1, -1, -1):
...     del list_[i]
... 
>>> list_
[]

或者使用while循环:

i = len(list_)
while i:
    i -= 1
    del list_[i]

所以在你的例子中,代码看起来像

users[:] = [user for user in users if specs in BIO[user]['follows']]

因为这是一个过滤工作,最好是用列表理解来完成的。[:]的要点是它分配给列表的一个片段,而不是删除对列表的引用。这意味着对列表的其他引用都将被更新。它基本上是到位的,只是在覆盖原始列表之前生成了一个拷贝。为了完整起见,下面是如何使用while循环来完成它。在

i = len(users)
while i:
    i -= 1
    if specs not in BIO[users[i]]['follows']:
        del users[i]

如果你想把它做好,你可以这样做。这里没有名单的副本。在

为什么要迭代?在

>>> un = ['PerezHilton', 'tomCruise', 'q', 'p']
>>> un.remove('p')
>>> un
['PerezHilton', 'tomCruise', 'q']

相关问题 更多 >

    热门问题