Reputation: 149
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 ?
Upvotes: 11
Views: 8845
Reputation: 11
a, b = [10,20,30], [11,2,40]
c = [x if x > y else y for x, y in zip(a, b)]
print(c)
Output: [11,20,40]
Upvotes: 1
Reputation: 149806
You could use zip()
and max()
in a list comprehension:
>>> L1 = [2,4,1,6]
>>> L2 = [1,5,2,3]
>>> [*map(max, zip(L1, L2))]
[2, 5, 2, 6]
If you can use numpy
, it's very simple with the numpy.maximum()
ufunc:
>>> import numpy as np
>>> arr1 = np.array([2, 4, 1, 6])
>>> arr2 = np.array([1, 5, 2, 3])
>>> np.maximum(arr1, arr2)
array([2, 5, 2, 6])
Upvotes: 6
Reputation: 700
Using List comprehension
l=[1,2,7]
m=[4,5,6]
max=[(l[i] if l[i]>m[i] else m[i] ) for i in range(0,len(l))]
print(max)
Upvotes: -1
Reputation: 1091
Here is a quick fix, in one set of iterations!
list_a = [2,4,1,6]
list_b = [1,5,2,3]
max_list = [value if list_b[index]<value else list_b[index] for index, value in enumerate(list_a)]
print(max_list)
Displays: [2, 5, 2, 6]
Upvotes: 1
Reputation: 66805
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)]
Upvotes: 10