一些奇怪的行为Python列表和dict

一些奇怪的行为Python列表和dict

本文介绍了一些奇怪的行为Python列表和dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释为什么这种情况发生在列表中,以及如何在附加到另一个列表之后清除列表?

 >> > t = {} 
>>>> t [m] = []
>>>> t
{'m':[]}
>>> t [m]。append('qweasdasd aweter')
>>> t [m]。append('asdasdaf ghghdhj')
>>> t
{'m':['qweasdasd aweter','asdasdaf ghghdhj']}
>>> r = []
>>> r.append(t)
>>>> r
[{'m':['qweasdasd aweter','asdasdaf ghghdhj']}]
>>> t [m] = []
>>>> r
[{'m':[]}]


解决方案>

这是一个正常的行为。 Python使用引用来存储元素。
当您执行 r.append(t) python将在中存储 t [R 。如果您稍后修改 t r 中的 t 将也被修改,因为它是相同的对象。



如果你想使 t 独立于存储在 r 你必须复制它。查看模块。


Can anyone explain why this happened with list and how to clean list after appending to another list?

>>> t = {}
>>> t["m"] = []
>>> t
{'m': []}
>>> t["m"].append('qweasdasd aweter')
>>> t["m"].append('asdasdaf ghghdhj')
>>> t
{'m': ['qweasdasd aweter', 'asdasdaf ghghdhj']}
>>> r = []
>>> r.append(t)
>>> r
[{'m': ['qweasdasd aweter', 'asdasdaf ghghdhj']}]
>>> t["m"] = []
>>> r
[{'m': []}]
解决方案

That's a normal behaviour. Python uses references to store elements.When you do r.append(t) python will store t in r. If you modify t later, t in r will be also modified because it's the same object.

If you want to make t independant from the value stored in r you have to copy it. Look at the copy module.

这篇关于一些奇怪的行为Python列表和dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:19