我有一个以给定格式呈现的列表:
[['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']]
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 ...
替换赋值语句,这样列表推导的结果就会被塞回原始列表中。 - SingleNegationEliminationpeople = [p for p in ...
,这样会更快一些,因为它避免了一些(但并不是非常多的)复制。 - SingleNegationEliminationpeople[:] = [p for p in people if all(p)]
。这与删除不符合条件的元素并将结果分配回原始列表相同。请注意保留HTML标记。[1, 2, 3, 4, 5, 6...]
^
初始时,这是列表的状态;现在假设移除了1并且循环进入列表的第二个项目:
[2, 3, 4, 5, 6...]
^
And so on.
在迭代列表时删除其中的元素是一个不好的想法。因此,可以尝试以下方法之一(另外,我认为您的条件不是您想要的 - 我已经修复了它):
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
for i, (first, last) in enumerate(people):
的语句,其中i
将会是 0、1、2 等等。 - Chris Morgan