【问题标题】:Python 3 - Get n greatest values in dict [closed]Python 3 - 在dict中获取n个最大值[关闭]
【发布时间】:2017-11-07 04:08:24
【问题描述】:

我有一个字典,字符串作为键,列表作为值,并且想要找到具有最长列表(长度)的 n 个键。

我该如何解决这个问题?

【问题讨论】:

  • 显示您尝试过的内容。我建议使用 heapq 模块。
  • 发布你的代码你尝试了什么
  • 您真正需要什么?不明白你的问题。请详细说明您的问题。

标签: python list python-3.x dictionary


【解决方案1】:

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

这里是 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

我不知道这是否是您要查找的内容,请发布更多详细信息以获得更详细的答案。

【讨论】:

    【解决方案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')
    

    如果您关心持久性,请使用 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2018-10-06
      • 1970-01-01
      相关资源
      最近更新 更多