Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine elements of two lists with if statement in python

Tags:

python

list

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.

like image 768
Soros Avatar asked Dec 06 '25 09:12

Soros


2 Answers

You can use max and list comprehension.

result = [max(pair) for pair in zip(R1, R2)]
print result
like image 60
stamaimer Avatar answered Dec 07 '25 22:12

stamaimer


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]
like image 44
AChampion Avatar answered Dec 07 '25 23:12

AChampion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!