繁体   English   中英

Python:如何获取字典中特定组的最大值?

[英]Python: how to get the max value of a specific group in a dictionary?

所以我发现要获得最大的字典值,我可以这样做:

dict[max(dict, key=dict.get)]

我的字典看起来像这样:{article_title:链接到该字典的文章数有多少}

示例:{'10世纪':2,'波兰':0,'墨西哥':11}

从group()中,我得到一个元组列表(article_title,article对象),例如:[(Mexico,Mexico()),(Poland,Poland())]

对于该组,我想检查一下article_title可能具有的最大值。

但是,如何找到特定键组的字典值? 我真的迷路了...我认为我写的没有道理:

dict = my dictionary
group_of_keys = group()  # returns specific list of tuples. The first term of the tuple is my key, the second is irrelevant
max_value = dict[max(dict[group_of_keys], key=dict.get)]

请帮助!

我假设group()返回一个list of keys 如果是这样,您可以获取这些键的值,然后从中找到最大值。

max(map(dict.get, groups()))

编辑:正如您澄清, group()返回(article_title, article_object)的元组,并且您希望article_title作为键,我们可以做的就是获取这些键的值作为dict.get(title) for title, article in group()然后在这些值中找到最大值。 因此,您的问题的答案是:

max(dict.get(title) for title, article in group())

小提示: dict不是变量的好名字,因为它遮盖了python的保留关键字dict

按组,我假设您是指密钥的子集

my_dict = {} # your dictionary
group = get_group(my_dict)
# since your group returns tuples of (key, something else)
group = [ i[0] for i in group ]
max_group_key = max(group, my_dict.get)
max_group_value = my_dict[max_group_key]

为了清楚起见,我正在用一个月的温度字典。 max_key会告诉我温度最高的月份。 max_group_key会告诉我该组中温度最高的月份。

temperature = {
    "jan": 17, "feb": 18, "mar": 19, "apr": 24, "may": 26, 
    "jun": 25, "jul": 22, "aug": 21, "sep": 20, "oct": 20,
    "nov": 18, "dec": 15
}

# hottest month
max_key = max(temperature, key=temperature.get)
max_val = temperature[max_key]

print("hottest month: {0}, temperature: {1}".format(max_key, max_val))

# only for a few months
group = [ ("jan", "foo"), ("feb", "bar"), ("jun", "baz") ]
group = [ i[0] for i in group ]
max_group_key = max(group, key=temperature.get)
max_group_val = temperature[max_group_key]

print("hottest month: {0}, temperature: {1}".format(max_group_key, max_group_val))

暂无
暂无

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

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