python3在di中获得n个最大值

2024-04-20 11:00:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dict,以字符串作为键,以列表作为值,并希望找到具有最长列表(长度)的n个键。你知道吗

我如何处理这个问题?你知道吗


Tags: 字符串列表dict个键
2条回答

如果你有你所描述的字典

>>> 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')

如果你关心持久性,那就用有序的方法

>>> 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')

Fromhere:我看到您可以从字典中构建排序列表。就复杂性而言,这可能不是最好的方法。你知道吗

下面是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

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

相关问题 更多 >