【问题标题】:Finding all the dicts of max len in a list of dicts在字典列表中查找 max len 的所有字典
【发布时间】:2018-12-13 23:45:29
【问题描述】:

我有一个字典列表

ld = [{'a': 1}, {'b': 2, 'c': 3}, {'d': 4, 'e': 5}]

我需要从我的列表中获取所有长度最长的元素,即

{'b': 2, 'c': 3}{'d': 4, 'e': 5}

我对 Python 不是很了解,但我发现:

>>> max(ld, key=len)
{'b': 2, 'c': 3}  

还有一个更好的解决方案,它返回最长字典的索引:

>>> max(enumerate(ld), key=lambda tup: len(tup[1]))
(1, {'b': 2, 'c': 3})

我想使用一个返回类似的表达式

(1: {'b': 2, 'c': 3}, 2: {'d': 4, 'e': 5})

我觉得我离解决方案不远(或者也许我离解决方案不远),但我只是不知道如何得到它。

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    找到最大长度,然后使用字典推导来找到该长度的字典

    max_l = len(max(ld, key=len))
    result = {i: d for i, d in enumerate(ld) if len(d) == max_l}
    

    这是您可以采用的最简单且更具可读性的方法

    下面是另一条路径,一种更好(但更冗长)的方法

    max_length = 0
    result = dict()
    
    for i, d in enumerate(ld):
        l = len(d)
    
        if l == max_length:
            result[i] = d
        elif l > max_length:
            max_length = l
            result = {i: d}
    

    这是最有效的方法。它只遍历完整的输入列表 1 次

    【讨论】:

    • 感谢您的深入回复!
    • 没问题,兄弟!尽管将我的答案标记为正确答案会很好。哈哈
    【解决方案2】:

    你可以在结构中找到最大字典的长度,然后使用列表推导:

    ld = [{'a':1}, {'b':2, 'c':3}, {'d':4, 'e':5}]
    _max = max(map(len, ld))
    new_result = dict(i for i in enumerate(ld) if len(i[-1]) == _max)
    

    输出:

    {1: {'b': 2, 'c': 3}, 2: {'d': 4, 'e': 5}}
    

    【讨论】:

      【解决方案3】:

      Ajax1234 提供了一个非常好的解决方案。如果您想要入门级的东西,这里有一个解决方案。

      ld = [{'a':1}, {'b':2, 'c':3}, {'d':4, 'e':5}]
      ans = dict()
      for value in ld:
           if len(value) in ans:
               ans[len(value)].append(value)
           else:
               ans[len(value)] = list()
               ans[len(value)].append(value)
      ans[max(ans)]
      

      基本上,您将所有内容添加到字典中以获得最大字典大小作为键,字典列表作为值,然后获得最大大小的字典列表。

      【讨论】:

        【解决方案4】:

        在 python 中有很多方法可以做到这一点。这是一个示例,它说明了一些不同的 Python 功能:

        ld = [{'a':1}, {'b':2, 'c':3}, {'d':4, 'e':5}]
        lengths = list(map(len, ld))  # [1, 2, 2]
        max_len = max(lengths)  # 2
        index_to_max_length_dictionaries = {
            index: dictionary
            for index, dictionary in enumerate(ld)
            if len(dictionary) == max_len
        }
        # output: {1: {'b': 2, 'c': 3}, 2: {'d': 4, 'e': 5}}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-27
          • 2021-12-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多