我有以下列表:
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代码实现这一点,无法导入额外的模块。
答案 0 :(得分:3)
您需要排序(使用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}