Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index wise maximum values of two lists

Tags:

python

list

Lets say I have 2 lists:

L1 = [2,4,1,6]
L2 = [1,5,2,3]

The output should be a new list that contains the biggest numbers found in L1 or L2 based on their position.

Example output:

L3 = [2, 5, 2, 6]

How to do it ?

like image 368
hsm Avatar asked Feb 06 '16 18:02

hsm


1 Answers

One of the possible solutions is to zip your lists, and then applying max operation element-wise, which can be obtained in python through call to functional map

L1 = [2,4,1,6]
L2 = [1,5,2,3]
L3 = map(max, zip(L1, L2)) # python2
L3 = list(map(max, zip(L1, L2))) # python3

or more pythonic through list comprehensions

L3 = [max(l1, l2) for l1, l2 in zip(L1, L2)]

or a bit shorter version using unpacking operation

L3 = [max(*l) for l in zip(L1, L2)]
like image 96
lejlot Avatar answered Sep 29 '22 02:09

lejlot