简体   繁体   English

如何从列表及其索引中找到最大元素?

[英]How to find maximum element from a list and its index?

I have a list with ordered dictionaries.我有一个带有有序词典的列表。 These ordered dictionaries have different sizes and can also have the same size(for example, 10 dictionaries can have the length of 30 and 20 dictionaries can have the length of 32).这些有序字典有不同的大小,也可以有相同的大小(例如,10 个字典的长度可以是 30,而 20 个字典的长度可以是 32)。 I want to find the maximum number of items a dictionary from the list has.我想从列表中找到字典的最大项目数。 I have tried this, which gets me the correct maximum length:我已经尝试过了,这让我得到了正确的最大长度:

maximum_len= max(len(dictionary_item) for dictionary_item in item_list)

But how can I find the dictionary fields for which the maximum_len is given?但是我怎样才能找到给出 maximum_len 的字典字段呢? Say that the maximum_len is 30, I want to also have the dictionary with the 30 keys printed.假设 maximum_len 是 30,我还想打印 30 个键的字典。 It can be any dictionary with the size 30, not a specific one.它可以是任何大小为 30 的字典,而不是特定的字典。 I just need the keys of that dictionary.我只需要那个字典的键。

Well you can always use filter:那么你总是可以使用过滤器:

output_dics=filter((lambda x: len(x)==maximum_len),item_list)

then you have all the dictionarys that satisfies the condition, pick a random one or the first one然后你有所有满足条件的字典,选择一个随机的或第一个

Don't know if this is the easiest or most elegant way to do it but you could just write a simple function that returns 2 values, the max_length you already calculated but also the dict that you can get via the.index method and the max_length of the object you were searching for.不知道这是否是最简单或最优雅的方法,但您可以编写一个简单的 function ,它返回 2 个值,即您已经计算的 max_length 以及您可以通过 .index 方法和 max_length 获得的 dict您正在搜索的 object。

im talking about something like this:我在谈论这样的事情:

    def get_max(list_of_dict):
        plot = []
        for dict_index, dictionary in enumerate(list_of_dict):
            plot.append(len(dictionary))

        return max(plot), list_of_dict[plot.index(max(plot))]

    maximum_len, max_dict = get_max(test)

tested it, works for my case, although i have just made myself a testlist with just 5 dicts of different length.对其进行了测试,适用于我的情况,尽管我刚刚为自己制作了一个只有 5 个不同长度的字典的测试列表。

EDIT: changed variable "dict" to "dictionary" to prevent it shadowing from outer scope.编辑:将变量“dict”更改为“dictionary”以防止它从外部 scope 阴影。

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

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