Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3-在dict中获取n个最大值_Python_List_Python 3.x_Dictionary - Fatal编程技术网

Python3-在dict中获取n个最大值

Python3-在dict中获取n个最大值,python,list,python-3.x,dictionary,Python,List,Python 3.x,Dictionary,我有一个dict,字符串作为键,列表作为值,并希望找到列表最长(长度)的n个键 我该如何解决这个问题呢?发件人:我知道你可以从词汇表中建立一个排序列表。就复杂性而言,这可能不是最好的方法 下面是python 3的示例: myDict = {'first':[1, 2, 3], 'second':[117, 2], 'third':[8, 37, 3, 4], 'fourth':[1], 'fifth': [3,2,3]} for i in sorted(myDict, key = lambda

我有一个dict,字符串作为键,列表作为值,并希望找到列表最长(长度)的n个键

我该如何解决这个问题呢?

发件人:我知道你可以从词汇表中建立一个排序列表。就复杂性而言,这可能不是最好的方法

下面是python 3的示例:

myDict = {'first':[1, 2, 3], 'second':[117, 2], 'third':[8, 37, 3, 4], 'fourth':[1], 'fifth': [3,2,3]}
for i in sorted(myDict, key = lambda x: len(myDict[x]), reverse=True):
    print i, len(myDict[i])
并打印出:

third 4
fifth 3
first 3
second 2
fourth 1

我不知道这是否是你想要的,发布更多细节以获得更详细的答案。

如果你有你描述的词典

>>> my_dict = {"first": [1, 2, 3], "second": [2, 3], "third": [1], "fourth": [1, 2, 3, 4]}
您可以使用以下方法获取字典中最长的n个值:

>>> sorted(my_dict.items(), key=lambda x: len(x[1]), reverse=True)[:2]

[('fourth', [1, 2, 3, 4]), ('first', [1, 2, 3])]
如果你想要钥匙的名字

>>> from operator import itemgetter
>>> tuple(map(itemgetter(0), sorted(my_dict.items(), key=lambda x: len(x[1]), reverse=True)[:2]))
('fourth', 'first')
如果您关心持久性,请使用OrderedDict

>>> from collections import OrderedDict

>>> OrderedDict(sorted(my_dict.items(), key=lambda x: len(x[1])))
OrderedDict([('third', [1]),
             ('second', [2, 3]),
             ('first', [1, 2, 3]),
             ('fourth', [1, 2, 3, 4])])
要按顺序对密钥进行排序,请执行以下操作:

>>> tuple(OrderedDict(sorted(my_dict.items(), key=lambda x: len(x[1]))).keys())[::-1]
('fourth', 'first', 'second', 'third')

展示你的尝试。我建议使用heapq模块。发布您的代码。您尝试过什么?您实际需要什么?我不明白你的问题。请详细说明您的问题。可能重复的