Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PythonDefaultDict引用_Python_Python 2.7_Defaultdict - Fatal编程技术网

PythonDefaultDict引用

PythonDefaultDict引用,python,python-2.7,defaultdict,Python,Python 2.7,Defaultdict,事实上,我不知道如何用恰当的标题来解释这个问题。欢迎任何版本 让我们看看这个例子 # python 2.7.x import collections d = collections.defaultdict(int) d['a'] = 2 d['b'] = 1 res = [d]* 2 res[0]['a'] -= 1 print res[1] # => defaultdict(<type 'int'>, {'a': 1, 'b': 1}) #python 2.7.x 导入集合

事实上,我不知道如何用恰当的标题来解释这个问题。欢迎任何版本

让我们看看这个例子

# python 2.7.x
import collections
d = collections.defaultdict(int)
d['a'] = 2
d['b'] = 1
res = [d]* 2
res[0]['a'] -= 1
print res[1]
# => defaultdict(<type 'int'>, {'a': 1, 'b': 1})
#python 2.7.x
导入集合
d=集合.defaultdict(int)
d['a']=2
d['b']=1
res=[d]*2
res[0]['a']-=1
打印资源[1]
#=>defaultdict(,{'a':1,'b':1})

我想知道为什么它会影响
res[1]

因为
res
是两个元素的列表,每个元素都是相同的对象:
d
,因为它们指向相同的对象。你可以通过跑步看到这一点

print(id(res[0]))
print(id(res[1]))

如果你不想让他们互相模仿,你可以复制一本字典

不使用中继器操作符
*
,它只是将引用复制到
d
,您可以使用列表理解和
d
的副本作为每次迭代的输出:

res = [d.copy() for _ in range(2)]

演示:

那么我如何重写它以使其唯一?您需要实例化几个defaultdict:
res=[collections.defaultdict(int),collections.defaultdict(int)]
或者更好的方法:
res=[collections.defaultdict(int)for uu in range(2)]
@cGlace,但这不是OP的代码打算做的。OP的代码旨在使用某些值初始化
defaultdict
,然后列出
defaultdict
的多个副本。您的建议将导致一个包含多个空
defaultdict
的列表。这是正确的,在这种情况下,您需要使用该模块。