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被难住了,但任何帮助都是感激的,谢谢
**抱歉,我现在修好了*
在这篇文章的底部,列出了一行中正确完成这一点的清单。以下是对这个问题的一些见解。在
不要做这样的事情:
因为糟糕和混乱的事情发生了。在
^{pr2}$每次删除项时,都会更改其余项的索引,这会使循环混乱。在遍历列表时,从列表中删除项的一个好方法是按索引执行,并向后工作,这样删除操作不会影响其余的迭代。这是更好的,因为如果删除第9个元素,那么第8个元素仍然是第8个元素,但是第10个元素将成为第9个元素。如果您已经处理过这个元素,那么您不关心它的索引是什么。在
或者使用
while
循环:所以在你的例子中,代码看起来像
因为这是一个过滤工作,最好是用列表理解来完成的。
[:]
的要点是它分配给列表的一个片段,而不是删除对列表的引用。这意味着对列表的其他引用都将被更新。它基本上是到位的,只是在覆盖原始列表之前生成了一个拷贝。为了完整起见,下面是如何使用while
循环来完成它。在如果你想把它做好,你可以这样做。这里没有名单的副本。在
为什么要迭代?在
相关问题 更多 >
编程相关推荐