【问题标题】:Updating integer values of a dictionary in python在python中更新字典的整数值
【发布时间】:2012-04-11 11:15:48
【问题描述】:

我正在创建一个缓存模拟器,我有一个字典,其中每个键关联了 3 个值,

我想知道当我通过数据文件时如何增加 noTaken 和 totalBranch 的值,因为我当前的方法不会更改值,查找的输出给我 (1,1,0) 或 ( 0,1,0) - 我需要增加前两个值

for line in datafile.readlines():
    items = line.split(' ')
    instruction = items[1]
    if lookup.has_key(instruction):
        if (taken == 1):
            lookup[instruction] = (noTaken + 1, totalBranch + 1, prediction)
        else:
            lookup[instruction] = (noTaken, totalBranch + 1, prediction)
    else:
        if (taken == 1):
            lookup[instruction] = (1, 1, prediction)
        else:
            lookup[instruction] = (0, 1, prediction)

(noTaken, prediction & totalBranch 都初始化为 0 以上) 提前致谢!

【问题讨论】:

    标签: python dictionary simulator


    【解决方案1】:

    一种更简洁的初始化方法是使用defaultdict,然后您可以直接引用dict值中的元素,例如

    from collections import defaultdict
    
    lookup = defaultdict(lambda: [0,0,0])
    
    lookup['a'][0] += 1
    lookup['b'][1] += 1
    lookup['a'][0] += 1
    
    print lookup
    

    输出:

    {'a': [2, 0, 0], 'b': [0, 1, 0]}
    

    另请注意,我将值默认为 list 而不是 tuple,以便我们可以就地修改值,tuple 是不可变的,无法修改

    【讨论】:

    • 请注意,OP 使用的是元组而不是列表,也许您可​​以在答案中指出这一点?
    • +1,因为defaultdict 是所有python问题的解决方案(是的,即使是那个,嘘!)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2022-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多