2011-03-31 42 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) 
相關問題