Home > Mobile >  How can I get the max of two lists
How can I get the max of two lists

Time:11-01

my goal is to get the max of two lists, for instance : list a -[1,2,3] list b - [0,4,1]

the desire resuls: 1,4,3 enter image description here


def ddh(a,b): v=[]

for i,j in range(len(a),len(b)):
    
    if a[i]>b[j]:
         v.append (a[i])
   
    else:
         v.append (b[j])
              
return v 
               

a=[1,2,555,9999] b=[22,4,444] ddh(a,b)


I tried to run the code and got just []

CodePudding user response:

You can use a list comprehension to iterate over the 2 lists at the same time using zip and take the max of every iteration:

list_a = [1, 2, 3]
list_b = [0, 4, 1]

maxes = [max(a, b) for a, b in zip(list_a, list_b)]
# [1, 4, 3]

You don't even need to unpack the tuple:

maxes = [max(values) for values in zip(list_a, list_b)]

And with map for a more functional approach:

maxes = list(map(max, zip(list_a, list_b)))

CodePudding user response:

max_zip = [max(a_, b_) for a_, b_ in zip(a, b)]

CodePudding user response:

def func(a,b):
    return [a if a>b else b for a,b in zip(a,b)]

print(func([1,2,3],[0,4,1]))

CodePudding user response:

This is a shorter and optimal version of your function.

def ddh(a,b):
    return [max(a[i],b[i]) for i in range(len(a))]

a=[1,2,3]
b=[0,4,1]
print (ddh(a,b))
  • Related