Question

I have a list of lists, let's call it array:

array=[[1,2,3,4],[2,3,4,5],[1,3,4,5]]

I need to be able to return the list(s) with the maximum number. In this case, I would need to return [2,3,4,5] and [1,3,4,5]

If I do max(array), I will get 2, because it only looks at the 0th element of each list.

I know this is a basic problem but I tried for 30 min to solve this using a for loop that finds the index of the maximum of each list and then returns the relevant lists but it is not working/and very inefficient.

Was it helpful?

Solution

# take the maximum from each tuple
>>> m1 = map(lambda tup: max(tup), array)
# take the maximum of all maximums
>>> m = max(m1)
# choose only tuples that contains m
>>> [tup for tup in array if m in tup]
[[2, 3, 4, 5], [1, 3, 4, 5]]

OTHER TIPS

array=[[1,2,3,4],[2,3,4,5],[1,3,4,5]]
max_lists = []
max_element = 0 # Considering only positive elements
for arr in array:
    cur_max = max(arr)
    if cur_max > max_element: # We find a new maximum
        max_element = cur_max
        max_lists = [arr]     # Forget previous list & create new one
    elif cur_max == max_element:
        max_lists.append(arr) # Lists with same maximum (till now)

print(max_lists)

Output of above code

[[2, 3, 4, 5], [1, 3, 4, 5]]

Note - This might not be most efficient, but I certainly do hope it is easily understandable! :)

You could also do it in only one short line (with extreme performance) as follows:

>>> import numpy as np
>>> a = np.asarray([[1,2,3,4],[2,3,4,5],[1,3,4,5]])

>>> a[np.nonzero(a==a.max())[0]]                    #really short

[[2 3 4 5]
 [1 3 4 5]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top