Python:从json fi获取max

2024-04-19 23:15:11 发布

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

我有这个json文件

myjson=[{u'faceRectangle': {u'height': 72, u'left': 214, u'top': 125, u'width': 72}, u'scores': {u'anger': 0.180509463,
 u'contempt': 1.50903434e-05, u'disgust': 0.008213697, u'fear': 0.418243885, u'happiness': 0.0259612668, u'neutral': 0.0001996803, u'sadness': 0.00102899456, u'surprise': 0.365827948}}]

我想从scores打印出概率最大的情绪,它的概率仅次于它。在

有什么建议吗?在

谢谢


Tags: 文件jsontop概率widthleftheighthappiness
1条回答
网友
1楼 · 发布于 2024-04-19 23:15:11

您可以使用内置的^{}函数和一个key来选择字典中每个项目的概率值:

>>> myjson = [{'faceRectangle': {'left': 214, 'width': 72, 'top': 125, 'height': 72}, 'scores': {'surprise': 0.365827948, 'disgust': 0.008213697, 'sadness': 0.00102899456, 'contempt': 1.50903434e-05, 'happiness': 0.0259612668, 'anger': 0.180509463, 'neutral': 0.0001996803, 'fear': 0.418243885}}]
>>> max(myjson[0]['scores'].items(), key=lambda x: x[1])
('fear', 0.418243885)

myjson[0]从列表中选择第一个字典,max()然后应用于嵌套的scores字典。在

您也可以使用operator.itemgetter()作为键函数:

^{pr2}$

相关问题 更多 >