简体   繁体   English

Python 在 2 元素列表中查找最大值

[英]Python Find max value in 2 element list

I have a 2 elements list like this one:我有一个像这样的 2 个元素列表:

[(0, 0.020449258), (1, 0.020540833), (2, 0.35077244), (3, 0.5467364), (4, 0.020515079), (5, 0.020485992), (6, 0.020499969)]

My goal is to fix the max value in the second column and return the first one.我的目标是修复第二列中的最大值并返回第一列。 So as per example I should be able to return 3 as it got the max value (0.5467364)因此,根据示例,我应该能够返回 3,因为它获得了最大值(0.5467364)

I'm able to find the max value using this code (where "result" is the list above):我可以使用此代码找到最大值(其中“结果”是上面的列表):

max_value = max(l[1] for l in result)

I'm struggling to get the index of such element to return the value =>3, I tryed:我正在努力让此类元素的索引返回值 => 3,我尝试过:

max_index = result.index(max_value)

and is returning this error:并返回此错误:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Thx谢谢

Can you try the following:您可以尝试以下方法:

arr = [
    (0, 0.020449258), 
    (1, 0.020540833), 
    (2, 0.35077244), 
    (3, 0.5467364), 
    (4, 0.020515079), 
    (5, 0.020485992), 
    (6, 0.020499969)
]
# sort the array based on the second element
arr = sorted(arr, key=lambda x: x[1], reverse=True)
# get the first element of the sorted array
print(arr[0][0])

Output Output

3

A simple answer could be:一个简单的答案可能是:

list = [(0, 0.020449258), (1, 0.020540833), (2, 0.35077244), (3, 0.5467364), (4, 0.020515079), (5, 0.020485992), (6, 0.020499969)]
max_index = 0
max_value = list[0][1]
for index in range(1, len(list)):
    if list[index][1] > max_value:
        max_value = list[index][1]
        max_index = index
print(max_index, max_value)

Complexity O(n)复杂度 O(n)

a = [(0, 0.020449258), (1, 0.020540833), (2, 0.35077244), (3, 0.5467364), (4, 0.020515079), (5, 0.020485992), (6, 0.020499969)]

value = (0, 0)
    for i in a:
        if i[1] > value[1]:
            value = i
print(value) --> (3, 0.5467364)
# or print value[0]

You could use list comprehension and numpy.argmax to break it down to 4 lines as follows:您可以使用列表理解和 numpy.argmax 将其分解为 4 行,如下所示:

list = [(0, 0.020449258), (1, 0.020540833), (2, 0.35077244), (3, 0.5467364), (4, 0.020515079), (5, 0.020485992), (6, 0.020499969)]

list.sort()   # The tuples are now sorted accordingly

values_list = [i[1] for i in list]               # List of the second elements
max_index = numpy.argmax(values_list)            # Index of max tuple
max_first_element = list[max_index][0]           # First element in that max tuple

print(max_first_element)

Please dont forget to import numpy at the top!请不要忘记在顶部导入 numpy!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM