gpt4 book ai didi

python - 如何知道哪本词典在我的列表中最关键

转载 作者:行者123 更新时间:2023-12-02 04:04:06 26 4
gpt4 key购买 nike

我有一个这种形式的字典列表

my_list = [{'notion': 'example'}, {'notion': 'another example', 'type': 'value'}, {'ex': 'other_ex'}]

我想获取列表中“最大”字典的索引。现在我有这个代码:

size = 0
for i, elem in enumerate(my_list):
if len(elem) > size:
index_to_save = i
size = len(elem)

现在我很确定有一种更快、更Python式的方法来实现这个目标。

有什么想法吗?

最佳答案

使用max()key=len:

>>> my_list = [{'notion': 'example'}, {'notion': 'another example', 'type': 'value'}, {'ex': 'other_ex'}]
>>> max(my_list, key=len)
{'notion': 'another example', 'type': 'value'}

如果您有多个具有相同最大键数的字典,并且您想返回全部它们,那么您可以使用列表理解进行过滤:

my_list = [
{"notion": "example"},
{"notion": "another example", "type": "value"},
{"notion": "another example", "type1": "value2"},
{"ex": "other_ex"},
]

max_length = max(map(len, my_list))
# or max(len(x) for x in my_list)

print([x for x in my_list if len(x) == max_length])
# [{'notion': 'another example', 'type': 'value'}, {'notion': 'another example', 'type1': 'value2'}]

或者另一种方法,按长度分组 collections.defaultdict ,然后取最大长度键的值:

from collections import defaultdict
from operator import itemgetter

my_list = [
{"notion": "example"},
{"notion": "another example", "type": "value"},
{"notion": "another example", "type1": "value2"},
{"ex": "other_ex"},
]

lengths = defaultdict(list)
for x in my_list:
lengths[len(x)].append(x)

print(max(lengths.items(), key=itemgetter(0))[1])
# [{'notion': 'another example', 'type': 'value'}, {'notion': 'another example', 'type1': 'value2'}]

关于python - 如何知道哪本词典在我的列表中最关键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59246759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com