Python:获取字典中元组每个字段的最大值
这是另一个关于列表和字典的问题。
我有一个字典,里面有单位名称和测试名称的列表:
dictA = {('unit1', 'test1'): 10, ('unit2', 'test1'): 78, ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}
units = ['unit1', 'unit2']
testnames = ['test1','test2']
我该如何找到每个测试名称对应的最大值呢:
我尝试了以下方法:
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 的值都是一样的!!
我哪里出错了?有没有更简单的方法?请给点建议。谢谢。
2 个回答
0
这段代码是用来处理一些特定的任务的。它可能涉及到一些计算、数据处理或者其他功能。具体来说,代码块中的内容会告诉你如何实现这些功能,或者如何解决某个问题。
如果你对代码的具体细节不太明白,可以把它想象成一个食谱。每一行代码就像是食谱中的一个步骤,按照顺序执行,就能得到你想要的结果。
总之,这段代码是一个工具,帮助你完成某些事情。只要你理解了每一步的作用,就能更好地使用它。
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}
6
>>> 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}
我想这应该能解决这个问题。