如何从包含 python 列表列表的字典中查找最大元素

how to find max element from dictionary that has list of lists in python

我是 python 的新手,我正在考虑编写一个函数,它基本上根据阈值输出字典中存在的子列表中最大的一个。

例如:champs = create_champion_index({'a': [[0, 10], [1, 20], [2,15]], 'b': [[0, 20], [1, 15], [2, 10]]}, 2)

 >>champs['a']
   [[1, 20], [2, 15]]
 >>champs['b']
   [[0, 20], [1, 15]]

所以根据阈值它应该输出具有最大值的子列表。在我的例子中,因为我提到 2 作为我的阈值,所以术语 'a' 的输出按升序显示两个最大的列表。

如果您有小的子列表,为了简单起见,您可以对排序后的 return 最后 n 个子列表进行排序,这假定 最大的 是具有最大和,如果你的意思是最大的子元素变化 summax:

def create_champion_index(d, n):
    new_d = {}
    # iterate over dict items key/values
    for k, v in d.items():
        # add `n` highest summed sublists from each value/list 
        new_d[k] = sorted(v, key=sum,reverse=True)[:n]
    return new_d # return new dict to access later

champs = create_champion_index({'a': [[0, 10], [1, 20], [2,15]], 'b': [[0, 20], [1, 15], [2, 10]]}, 2)

print(champs['a'])
print(champs['b'])
[[1, 20], [2, 15]]
[[0, 20], [1, 15]]

您可以在不排序的情况下多写几行,但对于短列表,使用排序就可以了。我还假设您的意思是 descending order 而不是 ascending 因为无论是 sum 还是 max 两个输出都是按降序排列的。

您需要添加更多逻辑以在键不存在且没有至少 n 个子列表时捕获。

我不确定你这里的 "threshold" 是什么意思,但我会使用你的变量名。因此,我理解 "threshold" 是每个列表中要输出的(最大)项目数,并且您希望 create_champion_index() 成为执行此操作的函数。我也不确定 "largest" 子列表是什么意思。你不是说 "longest" 因为你所有的子列表都是 2 个元素长。您可能指的是其中包含最大单个元素的子列表。我假设这就是你的意思。

以下内容似乎符合您的要求:

mydict = {'a': [[0, 10], [1, 20], [2,15]], 'b': [[0, 20], [1, 15], [2, 10]]}

def create_champion_index(in_dict, threshold=2):
    from heapq import nlargest
    from itertools import count
    retdict = {}
    for key in in_dict:
        this_list = in_dict[key]
        this_list_sublists_sorted = [sorted(x, reverse=True) for x in this_list]
        max_ndcs = nlargest(threshold, zip(this_list_sublists_sorted, count()))
        ndcs = [x[1] for x in max_ndcs]
        retlist = [this_list[i] for i in ndcs]
        retdict[key] = retlist
    return retdict

champs = create_champion_index(mydict, threshold=2)
print champs['a']
print champs['b']