繁体   English   中英

获取字典中给定键的最大值?

[英]Get the max value for given keys in a dictionary?

我有以下清单:

information = [[U1, b1, 12], [U1, b2, 15], [U1, b3, 1], [U2, b1, 6], [U2, b2, 7], [U2, b3, 43]]

我想从中返回一个字典,它将为我提供一对U和b的最大值,在给定列表的情况下,它将是:

bestvalues = {(U1, b2): 15, (U2, b3): 43}

我如何使用简单的python代码实现此目的,但无法导入额外的模块。

您需要排序(使用sorted() ,然后进行分组(使用itertools.groupby() ,然后在每个组上使用max()

from operator import itemgetter
from itertools import groupby

key = itemgetter(0)
bestvalues = {tuple(best[:2]): best[2] 
              for key, group in groupby(sorted(information, key=key), key=key)
              for best in (max(group, key=itemgetter(2)),)}

这些都是标准库模块。

如果没有任何导入,则必须循环两次。 首先将所有内容分组,然后找出每个组的最大值:

grouped = {}
for tup in information:
    grouped.setdefault(tup[0], []).append(tup)

bestvalues = {}
for group in grouped.itervalues():
    best = max(group, key=lambda g: g[2])
    bestvalues[tuple(best[:2])] = best[2]

演示:

>>> information = [['U1', 'b1', 12], ['U1', 'b2', 15], ['U1', 'b3', 1], ['U2', 'b1', 6], ['U2', 'b2', 7], ['U2', 'b3', 43]]
>>> key = itemgetter(0)
>>> {tuple(best[:2]): best[2] 
...               for key, group in groupby(sorted(information, key=key), key=key)
...               for best in (max(group, key=itemgetter(2)),)}
{('U1', 'b2'): 15, ('U2', 'b3'): 43}

是否进口:

>>> grouped = {}
>>> for tup in information:
...     grouped.setdefault(tup[0], []).append(tup)
... 
>>> bestvalues = {}
>>> for group in grouped.itervalues():
...     best = max(group, key=lambda g: g[2])
...     bestvalues[tuple(best[:2])] = best[2]
... 
>>> bestvalues
{('U1', 'b2'): 15, ('U2', 'b3'): 43}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM