python - 为什么 list.remove() 的行为不像人们预期的那样?

标签 python

from pprint import *

sites = [['a','b','c'],['d','e','f'],[1,2,3]]

pprint(sites)

for site in sites:
        sites.remove(site)

pprint(sites)

输出:

[['a', 'b', 'c'], ['d', 'e', 'f'], [1, 2, 3]]
[['d', 'e', 'f']]

为什么不是 None 或空列表 [] ?

最佳答案

这是因为您在迭代列表时正在修改它。你永远不应该那样做。

对于这样的事情,您应该复制列表并对其进行迭代。

for site in sites[:]:
    sites.remove(site)

关于python - 为什么 list.remove() 的行为不像人们预期的那样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7210578/

相关文章:

python - 矩阵操作: Subtract 2D Matrix and 3D Matrix in numpy

python - pysqlite 2.6.3 如何判断更新语句是否成功

Python:为什么itemgetter的返回类型不一致

python - 使用 Django 的用户帐户激活电子邮件

Python 单元测试在所有测试后运行函数

python - 在 celery 任务上调用 delay() 后,任务甚至需要 5 到 10 秒以上才能开始执行,以 redis 作为服务器

python - 使用 TensorFlow 出现奇怪的转换问题

python - 基于 Django 类的 View ,get_absolute_url 不工作

python - pandas 按天、周或月分组以获取时间戳

python - Pandas 的轻量级替代品