在字典列表中查找max len的所有字典 [英] Finding all the dicts of max len in a list of dicts
本文介绍了在字典列表中查找max len的所有字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字典列表
ld = [{'a': 1}, {'b': 2, 'c': 3}, {'d': 4, 'e': 5}]
我需要从列表中获取长度最长的所有元素,即
I need to get all the elements with the longest length from my list, i.e.
{'b': 2, 'c': 3}
和{'d': 4, 'e': 5}
.
我不太了解Python,但发现:
I'm not very knowledgeable in Python but I found that:
>>> max(ld, key=len)
{'b': 2, 'c': 3}
还有一个更好的解决方案,它返回最长字典的索引:
And, an even better solution that returns the index of the longest length dictionary:
>>> max(enumerate(ld), key=lambda tup: len(tup[1]))
(1, {'b': 2, 'c': 3})
我想使用一个返回类似
(1: {'b': 2, 'c': 3}, 2: {'d': 4, 'e': 5})
我觉得我离解决方案不远(或者也许我已经走了),但我只是不知道如何得到它.
and I feel like I'm not far from the solution (or maybe I am) but I just don't know how to get it.
推荐答案
您可以在结构中找到最大字典的长度,然后使用列表推导:
You can find the length of the maximum dictionary in the structure, and then use a list comprehension:
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}}
这篇关于在字典列表中查找max len的所有字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文