【问题标题】:Python: getting max of a of a {(tuple): value } dictionary per fieldname in tuplePython:获取元组中每个字段名的 {(tuple): value } 字典的最大值
【发布时间】:2011-03-21 16:22:04
【问题描述】:

另一个列表字典问题。

我有一个列表中包含单元名称和测试名称的字典,如下所示:

dictA = {('unit1', 'test1'): 10,  ('unit2', 'test1'): 78,  ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}

units = ['unit1', 'unit2'] 
testnames = ['test1','test2']

我们如何在 testnames 中找到每个测试的最大值:

我尝试如下:

def max(dict, testnames_array):
    maxdict = {}
    maxlist = []
    temp = []
    for testname in testnames_array:
        for (xunit, xtestname), value in dict.items():
            if xtestname == testname:
                if not isinstance(value, str):
                    temp.append(value)
            temp = filter(None, temp)
            stats = corestats.Stats(temp) 
            k = stats.max() #finds the max of a list using another module
            maxdict[testname] = k
    maxlist.append(maxdict)
    maxlist.insert(0,{'Type':'MAX'})
    return maxlist

现在的问题是我得到了输出:

[{'Type':'MAX'}, {'test1': xx}, {'test2':xx}]

其中 xx 都作为相同的值返回!!

我的错在哪里? 有更简单的方法吗? 请指教。谢谢。

【问题讨论】:

    标签: python list dictionary max tuples


    【解决方案1】:
    >>> dictA = {('unit1', 'test1'): 10,  ('unit2', 'test1'): 78,  ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}
    >>> maxDict={}
    >>> for (unitName,testName),grade in dictA.items():
        maxDict[testName]=max(maxDict.get(testName,0),grade)
    
    
    >>> maxDict
    {'test1': 78, 'test2': 45}
    

    我想这应该可以解决它。

    【讨论】:

    • +1 与我的回答类似,但您先到了那里。 (删除我的)
    • @Shawn:刚看到你的回答,我以为我发了两遍:)
    • +1 for for (unitName,testName),grade - 我不知道这是可能的!
    • 我可以知道这里发生了什么:maxDict.get(testName,0),grade 吗?
    • @siva: maxDict.get(testName,0) 表示返回 maxDict 字典中 testName 的值。如果键不存在,则返回 0。max(maxDict.get(testName,0),grade) 将旧等级与新等级进行比较,并返回最大的等级。因此,我们将每个测试的最高值与新的迭代值进行比较;如果新值更高,则成为最高值。
    【解决方案2】:
    dictA = {('unit1', 'test1'): 10,  ('unit2', 'test1'): 78,  ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}
    
    def maxIndex(d, field=0):
        best = {}
        for k,v in d.iteritems():
            index = k[field]
            try:
                old_v = best[index]
                best[index] = max(v, old_v)
            except KeyError:
                best[index] = v
        return best
    
    maxIndex(dictA, 0)  # -> {'unit1': 45, 'unit2': 78}
    maxIndex(dictA, 1)  # -> {'test1': 78, 'test2': 45}
    

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 1970-01-01
      • 2016-02-24
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 2017-03-05
      相关资源
      最近更新 更多