I am trying to merge two lists depend on the criteria. I have following codes.
R1=[10,20,30,40,50]
R2=[5,10,45,40,45]
for n,m in zip(R1,R2):
if n>m:
print(n)
else:
print(m)
When I run above code,the results is :
10
20
45
40
50
I don't know how to get that results as a new list like this:
results=[10,20,45,40,50]
How can I do this? Thanks in advance.
You can use max and list comprehension.
result = [max(pair) for pair in zip(R1, R2)]
print result
Create a new list and append() the result:
In []:
R1=[10,20,30,40,50]
R2=[5,10,45,40,45]
results = []
for n, m in zip(R1,R2):
if n>m:
results.append(n)
else:
results.append(m)
results
Out[]:
[10, 20, 45, 40, 50]
You can look at a list comprehension to do the same thing:
In []:
results = [n if n>m else m for n, m in zip(R1, R2)]
results
Out[]:
[10, 20, 45, 40, 50]
Or even more simply:
In []:
results = [max(x) for x in zip(R1, R2)]
results
Out[]:
[10, 20, 45, 40, 50]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With