例如,如果给定的字典如下:
dic = {('K1', 'S1'): 4.999997655759467,
('k1', 'K2'): 6.1999036349232375,
('K1', 'K4'): 7.999999999999876,
('K2', 'K1'): 6.199940422452897,
('K2', 'K3'): 7.999999999999876,
('K2', 'K5'): 6.199962763954776,
('K3', 'K2'): 6.199997321675397,
('K3', 'K6'): 7.999998023783301,
('K3', 'S2'): 9.999999999999911,
('K4', 'S1'): 9.999999999999911,
('K4', 'K1'): 6.199999975663285,
('K4', 'K5'): 6.19999999303405,
('K5', 'K2'): 6.199989058277423,
('K5', 'K4'): 7.999999999999876,
('K5', 'K6'): 7.999950953156936,
('K6', 'S2'): 9.999999999999911,
('K6', 'K3'): 7.999641214892367,
('K6', 'K5'): 6.19980050493078}
所需的输出如下:
{('K1', 'K4'): 7.999999999999876,
('K2', 'K3'): 7.999999999999876,
('K3', 'S2'): 9.999999999999911,
('K4', 'S1'): 9.999999999999911,
('K5', 'K4'): 7.999999999999876,
('K6', 'S2'): 9.999999999999911}
我实现了以下功能,但不幸的是,它只能获取值,而没有获取对应的键。
def getMaxForX(number):
return max([v for k, v in dic.items() if k[0] == number])
我不完全了解字典的最大键和值的概念吗?
请提出如何解决此问题的建议。
答案 0 :(得分:0)
我想您只是附加值(v)而不是键(k)。因此,将return
的逻辑更新为
return max([k, v for k, v in Q_values.items() if k[0] == number])
答案 1 :(得分:0)
因此,您想按键的第一个元素(K1, K2, K3, ...
)进行分组,然后根据该值找到每个分组的最大值:
>>> from itertools import groupby
>>> sortkey = lambda i: i[0][0].lower()
>>> groups = groupby(sorted(dic.items(), key=sortkey), key=sortkey)
>>> result = dict(max(v, key=lambda i: i[1]) for k, v in groups)
>>> result
{('K1', 'K4'): 7.999999999999876, ('K2', 'K3'): 7.999999999999876, ('K3', 'S2'): 9.999999999999911, ('K4', 'S1'): 9.999999999999911, ('K5', 'K4'): 7.999999999999876, ('K6', 'S2'): 9.999999999999911}
NB:分组时我使用了sortkey
,因为示例中的键之一具有不同的大小写。如果那只是一个错字,您可以忽略它。