【问题标题】:performing calculations on dictionary values对字典值执行计算
【发布时间】:2012-11-30 20:24:54
【问题描述】:

我有一本字典:

adict = {'key1':{'t1':{'thedec':.078, 'theint':1000, 'thechar':100},
                          't2':{'thedec':.0645, 'theint':10, 'thechar':5},
                          't3':{'thedec':.0871, 'theint':250, 'thechar':45},
                          't4':{'thedec':.0842, 'theint':200, 'thechar':37},
                          't5':{'thedec':.054, 'theint':409, 'thechar':82},
                          't6':{'thedec':.055, 'theint':350, 'thechar':60}}}

我使用以下循环,以便我可以将“theint”的值配对到一个向量中,以便最终我可以轻松地对它们执行统计计算:

for k1 in adict:
    x = []
    for t, record in sorted(adict[k1].items(), key = lambda(k,v):v['thedec']):
        x.append(record['theint'])
    y = [0]*(len(x)/2)
    for i in xrange(0,len(x),2):
        y[i/2] = sum(x[i:i+2])

我想知道是否: 1. 有一种比使用 .append() 更快的方法来提取 'theint' 的值 2.我可以采用一种方法,例如,所有“theint”值的平均值 3. 有一种方法可以让我在一个字典中循环遍历,这样我就可以以某种方式跳过这一步 首先复制所有值,然后立即将它们作为求和对添加到向量中。

感谢您的帮助。

【问题讨论】:

    标签: python list dictionary iterator


    【解决方案1】:
    >>> [x['theint'] + y['theint'] for x, y in zip(*[iter(sorted(adict['key1'].values(), key=operator.itemgetter('thedec')))] * 2)]
    [759, 1010, 450]
    

    【讨论】:

    • @ignacio Vazquez-Abrams,谢谢。我试图把它拆开。我真的不明白 [iterator_object] 是什么意思。我们如何在迭代器对象上使用 zip ?我了解这段代码的作用,但不了解如何。需要解释一下吗?
    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 2012-12-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多