我有一份字典清单-
houses = ['a', 'b', 'c']
rarity_values = {'Common':0,'uncommon':0}
rarity = {}.fromkeys([i for i in houses],rarity_values) # creates dictionary of id
print(rarity)
# {'a': {'Common': 0, 'uncommon': 0}, 'b': {'Common': 0, 'uncommon': 0}, 'c': {'Common': 0, 'uncommon': 0}}
我正在浏览某个文档,我想计算每个文档中常见事件发生的次数
house
. 如果我看到两个
Commons
对于
house a
和一个不寻常的房子
b
# {'a': {'Common': 2, 'uncommon': 0}, 'b': {'Common': 0, 'uncommon': 1}, 'c': {'Common': 0, 'uncommon': 0}}
Common
任何人
,它会为所有这些对象递增。
print('a (before increment)',rarity['a']['Common'])
print('b (before increment)',rarity['b']['Common'])
rarity['b']['Common'] += 1
print('a (after increment)',rarity['a']['Common'])
print('b (after increment)',rarity['b']['Common'])
产出
a (before increment) 0
b (before increment) 0
a (after increment) 1
b (after increment) 1
而不是
a (before increment) 0
b (before increment) 0
a (after increment) 0
b (after increment) 1
到1点。
{'a': {'Common': 1, 'uncommon': 0}, 'b': {'Common': 1, 'uncommon': 0}, 'c': {'Common': 1, 'uncommon': 0}}
{'a': {'Common': 0, 'uncommon': 0}, 'b': {'Common': 1, 'uncommon': 0}, 'c': {'Common': 0, 'uncommon': 0}}
有人知道我做错了什么吗?我应该用不同的方法来嵌套它吗?
谢谢