我有一本字典:
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.有一种更快的方法来提取'theint'的值而不是使用.append() 2.我可以采取一种方式,例如,所有'theint'值的平均值 3.有一种方法可以循环使用两个字典,这样我就可以跳过这一步 首先复制所有值,然后立即将它们作为求和对添加到矢量中。
感谢您的帮助。
答案 0 :(得分:3)
>>> [x['theint'] + y['theint'] for x, y in zip(*[iter(sorted(adict['key1'].values(), key=operator.itemgetter('thedec')))] * 2)]
[759, 1010, 450]