我有一个给定格式的列表:
[['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]
列表 ['Linus Torvalds', ''] 中有一些类似的元素,我想删除这些元素。那么为什么下面的代码不删除它们呢?
for i in people:
if(i[0] == '' or i[1] == ''):
print people.pop(people.index(i))
我有一个给定格式的列表:
[['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]
列表 ['Linus Torvalds', ''] 中有一些类似的元素,我想删除这些元素。那么为什么下面的代码不删除它们呢?
for i in people:
if(i[0] == '' or i[1] == ''):
print people.pop(people.index(i))
您在迭代列表时正在更改列表,这是您的问题的根源。一种有效的方法是
people[:] = [p for p in people if p[0] != '' and p[1] != '']
这样,将构建一个仅包含您想要的元素的新临时列表,然后在操作完成时将其分配给原始列表对象。
或者即使people[:] = [p for p in people if all(p)]
您想“就地”调整列表的大小。
您在迭代列表时正在修改列表的长度。这会导致您跳过值。当您从列表中弹出一项时,会发生以下情况(从这个答案中窃取):
[1, 2, 3, 4, 5, 6...]
^
这就是列表最初的状态;现在说 1 被删除,循环转到列表中的第二项:
[2, 3, 4, 5, 6...]
^
等等。
在迭代列表时从列表中删除内容是个坏主意。因此,请尝试其中一种(另外,我认为您的情况不是您想要的 - 我已经修复了它):
L = [['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']]
delete_these = []
for index, i in enumerate(L):
if not i[-1].strip():
delete_these.append(i)
for i in delete_these:
L.pop(i)
delete_these = map(lambda x: x-1, delete_these)
或者
L = [i for i in L if i[-1].strip()]
或者
answer = []
for i in L:
if i[-1].strip():
answer.append(i)
或者
i = 0
while i < len(L):
if not L[i][-1].strip():
L.pop(i)
else:
i += 1
希望这可以帮助