2012-12-13 95 views
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}}} 

我使用下面的循环,这样我可以在载体配对“的INT”的值,以便最终我可以轻松地使用对其执行统计计算:

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.有更快的方法来提取的“的INT”的值使用比.append() 2.是我可以采取一种方法,例如所有“的INT”的平均值 3.有一种方法,我可以通过两个的字典循环,使我能以某种方式跳过第一复印工序 所有的值,并马上去把它们添加到一个向量作为总结对。

感谢您的帮助。

回答

3
>>> [x['theint'] + y['theint'] for x, y in zip(*[iter(sorted(adict['key1'].values(), key=operator.itemgetter('thedec')))] * 2)] 
[759, 1010, 450] 
+0

方面!!!!!!!!! – Nikos

+0

@ignacio巴斯克斯 - 艾布拉姆斯,感谢。我试图把它分开。我真的不明白是什么[iterator_object]手段。我们如何在一个迭代器对象上使用zip?我明白这个代码的作用,但不是如何。谨慎解释? – cdelsola

+1

@ user1816858:http://stackoverflow.com/q/2233204/20862 –