python - Finding the index wise maximum values of two lists -


lets have 2 lists:

l1 = [2,4,1,6] l2 = [1,5,2,3] 

the output should new list contains biggest numbers found in l1 or l2 based on position.

example output:

l3 = [2, 5, 2, 6] 

how ?

one of possible solutions zip lists, , applying max operation element-wise, can obtained in python through call 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) l1, l2 in zip(l1, l2)] 

or bit shorter version using unpacking operation

l3 = [max(*l) l in zip(l1, l2)] 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -