person = {"name":' ',"id":0}
team = [ ]
for i in range(3):
x = person
x["id"] = i
team.append(x)
team[0]["name"]= "jack"
team[1]["name"]="Pony"
team[2]["name"]="alex"
print(team[1])
请问输出是什么样?
1{‘name’: ‘Pony’, ‘id’: 1}
2{‘name’: ‘Pony’, ‘id’: 2}
3{‘name’: ‘alex’, ‘id’: 2}
4{‘name’: ‘jack’, ‘id’: 0}
5{‘name’: ‘alex’, ‘id’: 2}
注意python中变量 赋值和C中的引用是一样的,引用内存中同一地址,可用Id()函数查看,这team中三个元素的输出结果是一模一样的,而且个一个]更改,其他二个列表也会跟着一起变动。
print (team)
[{‘name’: ‘alex’, ‘id’: 2}, {‘name’: ‘alex’, ‘id’: 2}, {‘name’: ‘alex’, ‘id’: 2}]
怎么解决,列表请坚持用方法***.copy()***去操作。
person = {"name":' ',"id":0}
team = [ ]
for i in range(3):
x = person.copy()
x["id"] = i
team.append(x)
team[0]["name"]= "jack"
team[1]["name"]="Pony"
team[2]["name"]="alex"
print(team)
[{‘name’: ‘jack’, ‘id’: 0}, {‘name’: ‘Pony’, ‘id’: 1}, {‘name’: ‘’, ‘id’: 2}]