我正在使用api以“标题”格式调用电影评论:[评分,评论]。在使用json.loads()函数之后,json列表看起来像这样:
listResult: {'Shawsank Redemption': [10, 'I love this movie so much'], 'Tropic Thunder': [9,'This was an awesome movie for sure'], 'Ted': [8, 'Hilarious throughout the entire movie']}
我必须返回评分最高的电影,我假设我必须使用for循环来查找最大值,但我不确定如何只访问列表中的评级值
答案 0 :(得分:4)
假设您的字典名称为listResult
(您应该更改,而不是列表),请使用内置的max
函数并提供自定义键功能:
>>> listResult = {'Shawsank Redemption': [10, 'I love this movie so much'], 'Tropic Thunder': [9,'This was an awesome movie for sure'], 'Ted': [8, 'Hilarious throughout the entire movie']}
>>> max(listResult, key=lambda movie: listResult[movie][0])
'Shawsank Redemption'
键功能用于定义电影名称的排序标准。对于每部电影,我们都会获得相应列表的第一个元素。
答案 1 :(得分:1)
以下是访问python列表的评级部分的方法。
listResult = {'Movie': [10, "I love this Movie"]}
rating = listResult["Movie"][0]
print rating // Prints 10
然后只需比较每个评分即可找到最大评分。