使用Python查找dict列表中两个值的max()项

2024-09-30 06:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据结构,包含一个包含dict的json编码列表。每个dict表示一个图像的数据。你知道吗

我想为整个结构中包含的所有dict找到具有最大“宽度”和最大“高度”值的dict。你知道吗

什么是Python式的方法?是否可以使用生成器表达式?你知道吗

[
'[{"imagePath": "full/efd5234517d9d20a7a47c3bf1860f6150a3bab6f.jpg", "percentageOfFirst": 0.2866666666666667, "height": 215.0, "width":
214.0, "imageSourceURL": "http://host/ca/I/iamge.png", "backgroundColor": null, "averageColor": "(197, 199, 203)", "md5": "cbd2eba6eb26b907901d1c932ab43a4f"}]',

'[{"imagePath": "full/72c2a2dabbbb2d3b245fafe85827b5b8f4df046b.jpg", "percentageOfFirst": 0.014079601990049751, "height": 62.0, "width":
275.0, "imageSourceURL": "http://host/logo.png", "backgroundColor": "white", "captionText": "SIEMNS", "averageColor": "(252, 253, 254)", "md5": "9951343e3ba782ba08549b2e14d8392c"}, {"imagePath": "full/ffe1119f36aa46eb72b52b4ff07c349fa32bea2e.jpg", "percentageOfFirst": 0.36909013605442176, "height": 523.0, "width":
400.0, "imageSourceURL": "http://host/image.png", "backgroundColor": "white", "averageColor": "(227, 228, 231)", "md5": "d9bee142cc4bdd457a1acfc8d37c8066"},
{"imagePath": "full/38ffd6eb550a1560ce736994ca85577d4df478e4.jpg", "percentageOfFirst": 0.6995127353266888, "height": 452.0, "width":
450.0, "imageSourceURL": "http://host/image.png", "backgroundColor": "white", "captionText": "nuMusmun", "averageColor": "(250, 250, 250)", "md5": "1b18fc0f9df4c1b2ca20ecda6537d5ac"}, {"imagePath": "full/ee3442b404f1a6f3fb77b448d475fbcee8b328b8.jpg", "percentageOfFirst": 0.10946727549467275, "height": 853.0, "width":
584.0, "imageSourceURL": "http://host/iamge.png", "backgroundColor": "white", "averageColor": "(202, 206, 212)", "md5": "a9cd43327d0f64aaf0ec5aafa3acf8ac"}]', '[{"imagePath": "full/5e24e5c1edf925bfddc0d66a483846729bcc9cbf.jpg", "percentageOfFirst": 0.22071519795657726, "height": 87.0, "width":
100.0, "imageSourceURL": "http://host/photos/image.png", "backgroundColor": "white", "averageColor": "(239, 239, 239)", "md5": "090b186f86de5c3a06ddea7e2c4bfd1a"}]'
]

Tags: httphostpngwidthmd5dictfulljpg
3条回答

在你有了实际的口述之后:

res = max(list_of_dicts, key=lambda d: d['width'])
lst = [
# your list
]

import json

# Parse your JSONs
parsed = map(json.loads, lst)

# Join sublists into one big list
joined = sum(parsed, [])

# Find the maximum
max_size = max(joined, key=lambda d: (d['width'] * d['height']))

print(max_size)

请注意,您的要求“具有最大“宽度”和最大“高度”的dict不一致:您如何比较800x600和900x500图像?所以我选择了最大尺寸的图像。你可以调整key到你想要的任何地方。你知道吗

可以为max()提供一个键函数。你知道吗

如果您有:

x = [{'image':1, 'width':5, 'height':5}, {'image':2, 'width':6, 'height':6}]

那么

max(x, key = lambda i:i['width'])

将获取具有最大宽度值的字典。你知道吗

相关问题 更多 >

    热门问题