【发布时间】:2018-02-07 07:56:11
【问题描述】:
我正在迭代一个列表,如下所示:
some_list = [1, 2, 3, 4]
another_list = [1, 2, 3, 4]
for idx, item in enumerate(some_list):
del some_list[idx]
for item in another_list:
another_list.remove(item)
当我打印出列表的内容时
>>> some_list
[2, 4]
>>> another_list
[2, 4]
我知道 Python 不支持在迭代 list 时对其进行修改,正确的方法是迭代列表的副本。但我想知道幕后究竟发生了什么,即为什么上面的 sn-p [2, 4] 的输出是?
【问题讨论】:
-
您是否使用调试器或类似pythontutor.com/visualize.html 的工具运行此程序?
-
我已经使用 ipython shell 运行了这个。
-
等等,为什么这个问题被否决了?迭代和删除很糟糕,但这个输出让我感到困惑。
-
第一项被删除,然后列表向左移动,因此索引增加,第二项被保留。以此类推。
-
unspecified.wordpress.com/2009/02/12/… 看起来 python 也有未定义的行为
标签: python list for-loop python-internals