繁体   English   中英

在字典列表中查找 max len 的所有字典

[英]Finding all the dicts of max len in a list of dicts

我有一个字典列表

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

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

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

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}}

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

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

在 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}}

找到最大长度,然后使用字典理解来查找具有该长度的字典

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 次

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM