2011-03-31 43 views
0

我有一个字典如下:的Python:通过返回一个字典的最大值其tupled密钥

counts = {('test1', 'alpha'): 2, 
      ('test2', 'beta'): 1, 
      ('test1', 'delta'): 1, 
      ('test2', 'gamma'): 2} 

我怎样才能返回其具有每个元组中的“α/β/γ/δ”最大值?

为test1,α,2 #because test1的具有 '阿尔法' 作为最高价值

test2的,伽玛,2个#because test2的具有 'γ' 作为最高价值

将这工作?

maxDict={} 
for (eachtest,pattern), counter in counts.items(): 
    maxDict[eachtest,pattern] = max(maxDict.get(eachtest,0),counter) 

谢谢。

回答

1

你是接近直角的。您只需要使用测试名称对字典进行索引,并记住模式名称及其值作为字典值。在我看来,使用max这里有点矫枉过正。更简单的代码也可以工作并且更易读:

maxDict = {} 
for (eachtest, pattern), counter in counts.iteritems(): 
    _, prev_max = maxDict.get(eachtest, ('', 0)) 
    if counter > prev_max: 
     maxDict[eachtest] = (pattern, counter) 

print maxDict 
# prints: {'test1': ('alpha', 2), 'test2': ('gamma', 2)} 
2

首先,将您的字典来测试名称映射到的(count, pattern)元组名单:

counts2 = collections.defaultdict(list) 
for (test, pattern), c in counts.iteritems(): 
    counts2[test] += (c, pattern) 

现在你可以很容易得到极大:

for test, patterns in counts2.iteritems(): 
    print test, max(patterns) 
相关问题