即使在某些字符串 Python 中不存在,也要在 json 中查找最大值

Find max value in json even when not existing in some strings Python

我有一个 json 这样的:

{
'tester': [{
    'bbox': [159.50451898338267, 184.94235347135182, 342.8551702886517, 443.9425698127003],
    'score': 0.9999966621398926,
    'post': 43.10764727758942,
    'class': 'Test'
}, {
    'bbox': [564.0261332136855, 14.13539395667492, 580.3409768964439, 38.84439850201004],
    'score': 0.9937067627906799
}, {
    'bbox': [462.02023603048644, 10.929288388749383, 477.8772119836293, 29.733179334594],
    'score': 0.9837657809257507
}],
'status': 'ok'

}

json 可以包含更多字符串。

我正在尝试使用以下代码从 Post 中获取最大值:

max_age = max(quality['tester'], key=lambda x: x['post'])

我面临的问题是密钥 Post 并不存在于每个字符串中,因此我在使用此代码时遇到密钥错误

假设您想忽略不包含 post 键的条目,这应该有效:

max_age = max(filter(lambda x: 'post' in x, quality['tester']), key=lambda x: x['post'])

您可能还想提供一个默认值(否则 max 会在序列为空时崩溃),如果您只对最大 post 值感兴趣,甚至可以使用此变体,而不是 post 值为最大值的条目:

max_age = max(x['post'] for x in quality['tester'] if 'post' in x))