python字典问题,求解答

qq_34537836 2017-09-26 01:44:37
问题:字典中嵌套子字典,各个子字典相同,改变其中一个子字典的值,其它子字典对应值也变了

代码:

结果:
...全文
134 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
chuifengde 2017-09-26
  • 打赏
  • 举报
回复
你看一看结构图
混沌鳄鱼 2017-09-26
  • 打赏
  • 举报
回复
引用 2 楼 qq_34537836 的回复:
[quote=引用 1 楼 xpresslink 的回复:] 把第7行改一下写成: red_result_dict[i+1] = dict(red_last_dict)
创建出来结构是正确的字典的,你看结果第一行就是[/quote] 你就乖乖试一下不行么?
qq_34537836 2017-09-26
  • 打赏
  • 举报
回复
引用 4 楼 u010099080 的回复:
你那种写法只是对同一对象添加了多个引用,他们指向的是同一个对象,所以你一改就全改了。

In [23]: id(red_result_dic[1])
Out[23]: 1966162609736

In [24]: id(red_result_dic[2])
Out[24]: 1966162609736

In [25]: id(red_result_dic[3])
Out[25]: 1966162609736

In [26]: id(red_result_dic[4])
Out[26]: 1966162609736
谢谢啦
qq_34537836 2017-09-26
  • 打赏
  • 举报
回复
引用 1 楼 xpresslink 的回复:
把第7行改一下写成: red_result_dict[i+1] = dict(red_last_dict)
对了,感谢您,是因为一开始red_result_dict字典的key都指向同一个red_last_dict字典吗?
secsilm 2017-09-26
  • 打赏
  • 举报
回复
你那种写法只是对同一对象添加了多个引用,他们指向的是同一个对象,所以你一改就全改了。

In [23]: id(red_result_dic[1])
Out[23]: 1966162609736

In [24]: id(red_result_dic[2])
Out[24]: 1966162609736

In [25]: id(red_result_dic[3])
Out[25]: 1966162609736

In [26]: id(red_result_dic[4])
Out[26]: 1966162609736
qq_34537836 2017-09-26
  • 打赏
  • 举报
回复
引用 1 楼 xpresslink 的回复:
把第7行改一下写成: red_result_dict[i+1] = dict(red_last_dict)
创建出来结构是正确的字典的,你看结果第一行就是
混沌鳄鱼 2017-09-26
  • 打赏
  • 举报
回复
把第7行改一下写成: red_result_dict[i+1] = dict(red_last_dict)

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧