小编Yas*_*pta的帖子

在迭代python列表时修改元素时这种行为背后的原因是什么

在下面的代码中,第一种类型的修改改变了原始列表,而在第二个列表中保持不变。为什么行为是这样?

temp = [{"a":"b"},{"c":"d"},{"e":"f"},{"a":"c"}]

for item in temp:
    if "a" in item:
        item["a"] = "x"
print(temp)
Run Code Online (Sandbox Code Playgroud)
temp = [{"a":"b"},{"c":"d"},{"e":"f"},{"a":"c"}]

for item in temp:
    item  = {}
print(temp)
Run Code Online (Sandbox Code Playgroud)

第一个的输出是 [{'a': 'x'}, {'c': 'd'}, {'e': 'f'}, {'a': 'x'}]

第二个是 [{'a': 'b'}, {'c': 'd'}, {'e': 'f'}, {'a': 'c'}]

Python 版本是 3.6.5

python dictionary list python-3.x

2
推荐指数
1
解决办法
127
查看次数

标签 统计

dictionary ×1

list ×1

python ×1

python-3.x ×1