Python从列表中删除项目
我有一个给定格式的列表:
[['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]
列表 ['Linus Torvalds', ''] 中有一些像这样的元素,我想删除它们。那么为什么下面的代码不删除它们呢?
for i in people:
if(i[0] == '' or i[1] == ''):
print people.pop(people.index(i))
I have a list in the given format:
[['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]
There are some elements like this in the list ['Linus Torvalds', ''] and I want to remove those. So why doesn't the following code remove them?
for i in people:
if(i[0] == '' or i[1] == ''):
print people.pop(people.index(i))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您在迭代列表时正在更改列表,这就是问题的根源。一种有效的方法是
构建仅包含所需元素的新临时列表,然后在操作完成时将其分配给原始列表对象。
You are changing the list while iterating over it and this is the source of your problems. An approach that works is
this way a new temporary list containing only the elements you want is built and then assigned to the original list object when the operation is complete.
或者甚至
people[:] = [p for p in people if all(p)]
如果您想“就地”调整列表大小。Or even
people[:] = [p for p in people if all(p)]
if you want to resize the list "in place".您在迭代列表时修改列表的长度。这会导致您跳过值。当您从列表中弹出一项时,会发生以下情况 (窃取这个答案):
这是列表最初的状态;现在假设 1 被删除,循环转到列表中的第二项:
依此类推。
You're modifying the list's length while iterating over it. That causes you to skip values. When you pop one item off the list, here's what happens (stealing from this answer):
That's the state of the list initially; now say 1 is removed and the loop goes to the second item in the list:
And so on.
在迭代列表时从列表中删除内容是一个坏主意。所以,尝试其中一种(另外,我认为你的情况不是你想要的 - 我已经修复了它):
或
或
或
希望这有帮助
It's a bad idea to remove things from a list as you iterate over it. So, try one of these instead (Also, I think your condition is not what you want it to be - I've fixed it):
OR
OR
OR
Hope this helps