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