I have a 2 elements list like this one:
[(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)
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:
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
CodePudding user response:
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
3
CodePudding user response:
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)
CodePudding user response:
Complexity 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]
