使用Python为dicts列表中的两个值查找带有max()的项



我有一个数据结构,它包含一个包含dict的json编码列表列表。每个dict表示关于图像的数据。

我想为整个结构中包含的所有dict找到具有最大"宽度"和最大"高度"值的dict。

什么是蟒蛇式的方式?可以使用生成器表达式吗?

[
'[{"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"}]'
]
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'])

将获得具有最高宽度值的字典。

在你有了实际的dicts:之后

res = max(list_of_dicts, key=lambda d: d['width'])

最新更新