python - 在列表之间移动 Python 元素

标签 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]

关于python - 在列表之间移动 Python 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9970174/

相关文章:

python - Pandas :按特定日期分组

python - 如何从 pandas 数据帧的列中提取最后一个单词

python - redis-py - 连接错误 : Socket closed on remote end - overload?

python - 多边形与圆的碰撞检测

python - 无法在 Python 中使用正则表达式检索所有组

python - 使用高斯(复数)整数生成毕达哥拉斯三元组

python - 在嵌套字典中获取键并将其关联到递归 Python 3 的路径

python - Slim Docker 镜像包含 git 存储库

python - 如何在Python中同时启动线程

python - 打开多个文件处理程序是否会减慢写入时间?