在列表之间移动Python元素
问题内容:
listA = [1,2,3]
listB = []
print listA
print listB
for i in listA:
if i >= 2:
listB.append(i)
listA.remove(i)
print listA
print listB
为什么只添加和删除元素“ 2”?
另外,当我注释掉“ listA.remove(i)”时,它会按预期工作。
问题答案:
您不应该修改要迭代的列表,这会导致令人惊讶的行为(因为迭代器在内部使用索引,并且这些索引通过删除元素来更改)。你可以做的是要遍历一个 复制
的listA
:
for i in listA[:]:
if i >= 2:
listB.append(i)
listA.remove(i)
例:
>>> listA = [1,2,3]
>>> listB = []
>>> for i in listA[:]:
... if i >= 2:
... listB.append(i)
... listA.remove(i)
...
>>> listA
[1]
>>> listB
[2, 3]
但是,采用功能性方法通常根本不修改原始列表,而是仅创建具有所需值的新列表通常会更清洁。您可以使用列表推导来优雅地做到这一点:
>>> lst = [1,2,3]
>>> small = [a for a in lst if a < 2]
>>> big = [a for a in lst if a >= 2]
>>> small
[1]
>>> big
[2, 3]