0

我有一本字典:

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 . 有一种方法可以让我在一个字典中循环遍历,这样我就可以以某种方式跳过首先复制所有值的步骤,然后立即将它们作为求和对添加到向量中。

谢谢您的帮助。

4

1 回答 1

3
>>> [x['theint'] + y['theint'] for x, y in zip(*[iter(sorted(adict['key1'].values(), key=operator.itemgetter('thedec')))] * 2)]
[759, 1010, 450]
于 2012-12-13T01:28:59.577 回答