I am trying to find the array with the largest first element, input would be
a = [[4.556, 20, 15], [4.772, 7, 4], [6.88, 5, 2], [2.33, 68, 9]]
output should be
[6.88,5,2]
because it has the largest first element
I am trying to find the array with the largest first element, input would be
a = [[4.556, 20, 15], [4.772, 7, 4], [6.88, 5, 2], [2.33, 68, 9]]
output should be
[6.88,5,2]
because it has the largest first element
max() will automatically start with the first element of the arrays when comparing. All you need to do is:
a = [[4.556, 20, 15], [4.772, 7, 4], [6.88, 5, 2], [2.33, 68, 9]]
max(a)
# [6.88, 5, 2]
If the first elements are equal, it will compare the second, etc.. This process of comparison is described in the data structure docs.
Use the key parameter of max:
from operator import itemgetter
a = [[4.556, 20, 15], [4.772, 7, 4], [6.88, 5, 2], [2.33, 68, 9]]
result = max(a, key=itemgetter(0))
print(result)
Output
[6.88, 5, 2]
The operator.itemgetter function just fetches the first position of the list, for example:
itemgetter(0)([1, 2, 3])
returns 1.
Based on @DaniMesejo's answer.
You can use lambda to save an import
max(a, key=lambda x: x[0])