代码之家  ›  专栏  ›  技术社区  ›  Micah Pearce

Python字典列表增量错误[重复]

  •  -1
  • Micah Pearce  · 技术社区  · 7 年前

    我有一份字典清单-

    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}}
    

    有人知道我做错了什么吗?我应该用不同的方法来嵌套它吗?

    谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   Anthony Kong    7 年前

    你应该使用字典理解。

    for i in houses:
        rarity[i] = dict(rarity_values)
    

    在原始代码中,您正在链接的同一个实例 rarity_values 至每个键“a”和“b”