简体   繁体   English

如何获取字典中某个键的最大值?

[英]How to get the maximum value of a key in dict?

I would like to get the URL of a video with maximum resolution.我想获得最高分辨率视频的 URL。

If I had the following dictionary, would it be easiest to get the URL of the video with the maximum size?如果我有以下字典,是否最容易获得最大尺寸的视频的 URL?

Is it best to split the size by partition, format the number into an int type, and then get the value?是不是最好按分区拆分大小,把数字格式化成int类型,然后取值?

videos = {
        'size_476_306': 'https://www.....',
        'size_560_360': 'https://www.....',
        'size_644_414': 'https://www.....',
        'size_720_480': 'https://www.....',
}

Solved解决了

I couldn't figure out lambda, so I implemented it in a different way.我想不出lambda,所以我用不同的方式实现了它。

for size, v_url in videos.items():

    max_size_info = size.split('_')
    split_size = int(max_size_info[1])
    size_array.append(split_size)
    video_array.append(v_url)

max_size = size_array.index(max(size_array))
if str(size_array[max_size]) in v_url:
    print(size,v_url)

Is it best to split the size by partition, format the number into an int type, and then get the value?是不是最好按分区拆分大小,把数字格式化成int类型,然后取值?

Yes, that's the way I'd do it:是的,我就是这样做的:

>>> max(videos.items(), key=lambda i: int.__mul__(*map(int, i[0].split("_")[1:])))
('size_720_480', 'https://www.....')

Here's a slightly more verbose version with a named function:这是一个更详细的版本,名为 function:

>>> def get_resolution(key: str) -> int:
...     """
...     Gets the resolution (as pixel area) from 'size_width_height'.
...     e.g. get_resolution("size_720_480") -> 345600
...     """
...     _, width, height = key.split("_")
...     return int(width) * int(height)
...
>>> max(videos, key=get_resolution)
'size_720_480'

Given that expression that gives us the largest key, we can easily get the corresponding value:给出给我们最大键的表达式,我们可以很容易地得到相应的值:

>>> videos[max(videos, key=get_resolution)]
'https://www.....'

or we could get the key, value pair by taking the max of items() , here using a much simpler lambda that just translates key, value into get_resolution(key) :或者我们可以通过取items()的最大值来获取键值对,这里使用更简单的lambda ,它只是将key, value对转换为get_resolution(key)

>>> max(videos.items(), key=lambda i: get_resolution(i[0]))
('size_720_480', 'https://www.....')

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

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