我有以下列表:獲取字典中給定鍵的最大值?
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代碼實現這一點,不能導入額外的模塊。
我有以下列表:獲取字典中給定鍵的最大值?
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}
錯字 - '操作符'。另外,'key:max' :) –
@SukritKalra:全部修復。 –
+1。我不知道現在是否應該刪除我的答案,而是在答案中更好地將其納入。 :) –
我不明白。你所有的配對都有不同的U或b。你如何選擇一對{U,b}? – njzk2