我没有庞大的列表,所以我更喜欢使用标准库。我试图初始化一个包含空值的字典(所以我稍后可以对它们进行数学运算)但是当我改变一个值时,其他值也会改变。
l = ['a', 'b', 'c']
d = {'CategoryA': dict.fromkeys(l, dict.fromkeys(l, 0)),
'CategoryB': dict.fromkeys(l, dict.fromkeys(l, 0)),
'CategoryC': dict.fromkeys(l, dict.fromkeys(l, 0))}
d['CategoryA']['a']['c'] += 1
print d['CategoryA']['a']['c']
print d['CategoryA']['b']['c']
print d['CategoryA']['c']['c']
这连续三次打印1次,但我希望它打印出1然后再打印0次。似乎最终的字典值是链接的。
我还尝试创建两个相同的列表(丑陋的代码),认为列表是链接的,但是没有修复它,我用这个更丑陋的代码获得相同的打印输出:
l1 = ['a', 'b', 'c']
l2 = ['a', 'b', 'c']
d = {'CategoryA': dict.fromkeys(l1, dict.fromkeys(l2, 0)),
'CategoryB': dict.fromkeys(l1, dict.fromkeys(l2, 0)),
'CategoryC': dict.fromkeys(l1, dict.fromkeys(l2, 0))}
d['CategoryA']['a']['c'] += 1
答案 0 :(得分:0)
所以问题是0(值)不是我认为的键。这解决了这个问题,但有没有比这个字典理解更可读的东西?
l = ['a', 'b', 'c']
d = {'CategoryA': dict((i, dict((i, 0) for i in l)) for i in l),
'CategoryB': dict((i, dict((i, 0) for i in l)) for i in l),
'CategoryC': dict((i, dict((i, 0) for i in l)) for i in l)}
d['CategoryA']['a']['c'] += 1
print d['CategoryA']['a']['c']
print d['CategoryA']['b']['c']
print d['CategoryA']['c']['c']
首先打印1,然后按预期打印两次。