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

2
  • 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 docs.scipy.org/doc/numpy-1.14.0/reference/generated/…) Commented May 10, 2018 at 15:56
  • Alex Hall answer is very good. Too bad it's a duplicate (nice dupe find BTW) Commented May 10, 2018 at 16:07

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

you could explain the not so known fact that map can iterate on several lists at once.
There is a small issue. It will not work when data contains only one sublist or is empty.
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)]

Comments

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])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.