aba*_*rik 0 python dictionary list
为什么在Python中,使用n*[dict()]来创建嵌套字典导致相同的字典对象?
>>> d = [(111, 2222), (3333, 4444), (555, 666)]
>>> d
[(111, 2222), (3333, 4444), (555, 666)]
>>> x = len(d) * [dict().copy()][:]
>>> x
[{}, {}, {}]
>>> x[0]['x'] = 'u'
>>> x # All entries of x gets modified
[{'x': 'u'}, {'x': 'u'}, {'x': 'u'}]
>>>
>>> x = [dict(), dict(), dict()]
>>> x
[{}, {}, {}]
>>> x[0]['x'] = 'u'
>>> x # only one entry of x gets modified
[{'x': 'u'}, {}, {}]
>>>
Run Code Online (Sandbox Code Playgroud)
在x = len(d) * [dict().copy()][:],该dict功能只运行一次.因此,所有三个词典都是相同的.如果你想要三个不同的词典,你需要运行三次,例如:
>>> x = [dict() for i in range(3)]
>>> x
[{}, {}, {}]
>>> x[0]['x'] = 'u'
>>> x
[{'x': 'u'}, {}, {}]
>>>
Run Code Online (Sandbox Code Playgroud)
Python不能繁殖名单,直到后它已创建列表.因此,当3 * [dict()]执行时,dict首先评估然后执行乘法.同样如此,3*[int(1)]但注意到最初可能看起来令人困惑的差异:
>>> x = 3*[int(1)]
>>> x
[1, 1, 1]
>>> x[0] = 2
>>> x
[2, 1, 1]
Run Code Online (Sandbox Code Playgroud)
从表面上看,这似乎与词典的乘法列表的情况不一致.这里的区别是,赋值语句x[0] = 2并没有修改的属性x[0]; 它取代 x[0]了新元素.因此,结果是不同的.
替换的概念也适用于词典.考虑:
>>> x = 3 * [dict()]
>>> x
[{}, {}, {}]
>>> x[0] = dict(x='u')
>>> x
[{'x': 'u'}, {}, {}]
Run Code Online (Sandbox Code Playgroud)
即使三个字典x开始时也是如此,该语句x[0] = dict(x='u')将用新的字典替换第一个字典.
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |