【问题标题】:Python: Returning max value of a dict by its tupled-keyPython:通过元组键返回字典的最大值
【发布时间】:2011-07-26 18:18:30
【问题描述】:

我的字典如下:

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

如何返回每个具有最大值的元组的“alpha/beta/gamma/delta”?

test1, alpha, 2 #因为 test1 的最高值是 'alpha'

test2, gamma, 2 #因为 test2 的最高值是 'gamma'

这行得通吗?

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

谢谢。

【问题讨论】:

    标签: python dictionary max tuples


    【解决方案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】:

      首先,转换您的 dict 以将测试名称映射到 (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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-21
        • 1970-01-01
        • 1970-01-01
        • 2013-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多