Soros
Soros

Reputation: 41

Combine elements of two lists with if statement in python

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.

Upvotes: 2

Views: 3440

Answers (5)

stamaimer
stamaimer

Reputation: 6475

You can use max and list comprehension.

result = [max(pair) for pair in zip(R1, R2)]
print result

Upvotes: 5

o11c
o11c

Reputation: 16036

Use map with multiple iterables:

>>> R1=[10,20,30,40,50]
>>> R2=[5,10,45,40,45]
>>> it = map(max, R1, R2)
>>> print(list(it))
[10, 20, 45, 40, 50]

(Generally, the place to look is in the itertools module, but in this case the function is actually builtin).

Upvotes: 0

Raymond Hettinger
Raymond Hettinger

Reputation: 226181

Functional solution

The map() and max() functions make short work of this problem:

>>> R1 = [10, 20, 30, 40, 50]
>>> R2 = [5, 10, 45, 40, 45]
>>> list(map(max, R1, R2))
[10, 20, 45, 40, 50]

List comprehension solution

Another technique to is to use a conditional expression in a list comprehension:

>>> [n if n>m else m for n, m in zip(R1, R2)]
[10, 20, 45, 40, 50]

Upvotes: 1

AChampion
AChampion

Reputation: 30258

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]

Upvotes: 3

Max
Max

Reputation: 1363

R1=[10,20,30,40,50]
R2=[5,10,45,40,45]
temp_list = []
for n,m in zip(R1,R2):
    if n>m:
        temp_list.append(n)
    else:
        temp_list.append(m)

print(temp_list)

this should work. you are trying to print each value, so it is printed on separate lines.

Upvotes: 0

Related Questions