I've got the following list of lists:
[[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0],
[1.0, 4],
[0, 0],
[0.75, 3],
[0.75, 3],
[0, 0],
[1.0, 4],
[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 0],
[0, 1],
[0, 2]]
I'm trying to get the index corresponding to the maximum value for every first element in the list.
I'm using this:
similarity_list.index(max([similarity_list[1]]))
and it's returning the following error:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I'm trying to use .any() or .all() but it's not working. What's wrong?
To get the item with the largest value in the first index of the sub array, you could use max
with a lambda that tells the max
function to only evaluate based on certain properties of the value (in this case the value at index zero).
>>> max_val = max(data, key=lambda v: v[0])
>>> max_val
[1.0, 4]
To then get the index of that value, you can use the simple index function on the list.
>>> max_index = data.index(max_val)
>>> max_index
6
You could get both values at once by enumerating the input list, which will allow you to include the index as part of the returned data. We just have to slightly change how we pull out the data in the lambda for which the max function uses to rank candidates.
>>> max_index, max_val = max(enumerate(data), key=lambda v: v[1][0])
>>> max_index, max_val
(6, [1.0, 4])
And to get just the index alone, you could find the max of the index values compared to their corresponding data in the list. Again, using a lambda to instruct the max function on how to evaluate candidates.
>>> max_index = max(range(len(data)), key=lambda i: data[i][0])
>>> max_index
6
Many ways to crack an egg!