简体   繁体   English

如何在字典的项目中找到包含最多元素的列表?

[英]How to find the list with most elements in the items of a dict?

Say that I have说我有

function(Dict[str, List[str]] -> List[str]

how could I return a list that contains the str in the Dict with most elements in the list?我如何返回一个包含列表中大多数元素的字典中的 str 的列表?

function({'a':['1','2'], 'b':['1'], 'c':['1', '2']})

['a', 'c']

The function should be able to still return the str even if more than one str has the most elements in the list just like the above example. function 应该仍然能够返回 str 即使多个 str 具有列表中的最多元素,就像上面的示例一样。 Thank you very much in advance!非常感谢您!

Get the max length first, then loop over the elements to filter those that have the max length:首先获取最大长度,然后遍历元素以过滤具有最大长度的元素:

def get_max(d):
    max_len = max(map(len,d.values()))
    return [k for k,v in d.items() if len(v)==max_len]

get_max({'a':['1','2'], 'b':['1'], 'c':['1', '2']})
# ['a', 'c']

One approach:一种方法:

def fun(d):
    current, res = 0, []
    for k, v in d.items():
        if len(v) > current:
            res = [k]
            current = len(v)
        elif len(v) == current:
            res.append(k)
            current = len(v)
    return res


final = fun({"a": ['1', '2'], "b": ['1'], "c": ['1', '2']})
print(final)

Output Output

['a', 'c']

Your function will look like this:您的 function 将如下所示:

def dict_to_max_list(mydict):
    for item in mydict.items():
        mydict[item[0]] = len(item[1])
    all_values = mydict.values()
    max_value = max(all_values)

    # Using list comprehension
    mylist = [x[0] for x in mydict.items() if x[1] == max_value]
    return mylist

The above function accepts a dict.上面的 function 接受一个字典。 Iterates through your dict and calculate the length of each list in your dict.遍历您的 dict 并计算 dict 中每个列表的长度。 And then returns list with maximum value using list comprehension.然后使用列表推导返回具有最大值的列表。

d1 = {'a':['1','2'], 'b':['1'], 'c':['1', '2']}
list1 = dict_to_max_list(d1)
print(list1)
def function(dict_list: dict):
    #set the max length to 0
    greatest_length = 0
    lists_with_greatest_length = []

    #for each list if the length is greater than greatest_length 
    #we overwrite lists_with_greatest_length with the new list and take its length as the largest.
    for (key, liste) in zip(dictt.keys(), dictt.values()):
        if len(liste) > greatest_length:
           greatest_length = len(liste)
           lists_with_greatest_length = [key]

        elif len(liste) == greatest_length:
           lists_with_greatest_length.append(key)

    return lists_with_greatest_length
 

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

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