相关疑难解决方法(0)

当您尝试在迭代时删除列表元素时会发生什么

我正在迭代一个列表如下:

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)
Run Code Online (Sandbox Code Playgroud)

当我打印出列表的内容时

>>> some_list
[2, 4]
>>> another_list
[2, 4]
Run Code Online (Sandbox Code Playgroud)

我知道Python不支持修改list迭代它,而正确的方法是迭代列表的副本(所以请不要downvote).但我想知道幕后究竟发生了什么,即为什么输出上面的片段[2, 4]

python for-loop list python-internals

4
推荐指数
1
解决办法
1271
查看次数

标签 统计

for-loop ×1

list ×1

python ×1

python-internals ×1