Python.Comparing numbers in 2 lists and finding max

岁酱吖の 提交于 2019-12-22 17:57:10

问题


I have 2 lists with elements like:

list1=[2,54,31,6,42]
list2=[4,98,43,3,2]

I want a def that compares the numbers and returns a 3rd list with the biggest one.

In this example the 3rd list would be:

list3=[4,98,43,6,42]

回答1:


Here's a simple def/function to zip() the two lists and then get max() and store it into a new list3 and returned:

list1=[2,54,31,6,42]
list2=[4,98,43,3,2]

def function(list1,list2): #def returns 3rd list 
    list3 = [max(value) for value in zip(list1, list2)]
    return list3
print(function(list1,list2)) # call def named function to print

Output:

[4, 98, 43, 6, 42]



回答2:


Use map() function:

In [4]: list(map(max, list1, list2))
Out[4]: [4, 98, 43, 6, 42]



回答3:


You can use list comprehension with max function.

>>> list1=[2,54,31,6,42];list2=[4,98,43,3,2]
>>> [max(i) for i in zip(list1,list2)]
[4, 98, 43, 6, 42]
>>> 


来源:https://stackoverflow.com/questions/40948253/python-comparing-numbers-in-2-lists-and-finding-max

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!