3

I need to find the max of all index items in a list, which is the efficient way, Does numpy have any function or efficient and best pythonic way, my list elements will length above 100, with each list with 20 elements.

eg:

[[1,2,3,4,5,6],[3,2,1,4,5,6],[4,3,2,1,5,6],[1,1,1,1,1,1]]
max_list = [4,3,3,4,5,6]

My list will length to around 100, with each inner list with 20 elements

Georgy
  • 12,464
  • 7
  • 65
  • 73
Thomas John
  • 2,138
  • 2
  • 22
  • 38
  • 2
    Not sure what your constraints are, but why not turn the list of lists into a numpy array and then take the max on whatever axis you prefer? (see https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.amax.html) – fgb May 10 '18 at 15:56
  • Alex Hall answer is very good. Too bad it's a duplicate (nice dupe find BTW) – Jean-François Fabre May 10 '18 at 16:07

3 Answers3

9

Solution without numpy:

data = [[1,2,3,4,5,6],[3,2,1,4,5,6],[4,3,2,1,5,6],[1,1,1,1,1,1]]
list(map(max, *data))

The list is not needed in Python 2 (or even in Python 3, depending on what you're going to do with the result)

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
3

Also without numpy (but with help of comment authors)

inp = [[1,2,3,4,5,6],[3,2,1,4,5,6],[4,3,2,1,5,6],[1,1,1,1,1,1]]
out = [max(s) for s in zip(*inp)]
VPfB
  • 14,927
  • 6
  • 41
  • 75
2

You can use the following:

a = np.array([[1,2,3,4,5,6],[3,2,1,4,5,6],[4,3,2,1,5,6],[1,1,1,1,1,1]])
a.max(0) #a.max(axis=0)

Which results in:

array([4, 3, 3, 4, 5, 6])
Sudheesh Singanamalla
  • 2,283
  • 3
  • 19
  • 36
llllllllll
  • 16,169
  • 4
  • 31
  • 54