在python列表中找到最大值和索引? [英] Find maximum value and index in a python list?
问题描述
我有一个像这样的python列表,
I have a python list that is like this,
[[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968], [12587982, 0.88], [12587984, 0.8484848484848485], [12587992, 0.7777777777777778], [12587995, 0.8070175438596491], [12588015, 0.4358974358974359], [12588023, 0.8985507246376812], [12588037, 0.5555555555555555], [12588042, 0.9473684210526315]]
此列表的最大长度为一千个元素,如何根据子数组中的第二项获取列表中的最大值,并获取最大值的索引(即第一个元素) python中的子数组?
This list can be up to thousand elements in length, how can I get the maximum value in the list according to the second item in the sub-array, and get the index of the maximum value which is the fist element in the sub-array in python?
推荐答案
使用 max
函数及其key
参数,仅使用第二个元素来比较列表中的元素.
Use the max
function and its key
parameter, to use only the second element to compare elements of the list.
例如,
>>> data = [[12587961, 0.7777777777777778], [12587970, 0.5172413793103449], [12587979, 0.3968253968253968].... [12588042, 0.9473684210
526315]]
>>> max(data, key=lambda item: item[1])
[12588042, 0.9473684210526315]
现在,如果只需要第一个元素,则只需简单地获取第一个元素,或者像这样将结果解压缩
Now, if you want just the first element, then you can simply get the first element alone, or just unpack the result, like this
>>> index, value = max(data, key=lambda item: item[1])
>>> index
12588042
>>> value
0.9473684210526315
如果要在具有最大值(第二个值)的所有元素中找到最大索引(第一个值),则可以这样做
If you want to find the maximum index (first value) out of all elements with the maximum value (second value), then you can do it like this
>>> _, max_value = max(data, key=lambda item: item[1])
>>> max(index for index, value in data if value == max_value)
您可以在单个迭代中完成相同的操作
You can do the same in a single iteration, like this
max_index = float("-inf")
max_value = float("-inf")
for index, value in data:
if value > max_value:
max_value = value
max_index = index
elif value == max_value:
max_index = max(max_index, index)
这篇关于在python列表中找到最大值和索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!