Skip to main content
 首页 » 编程设计

python之迭代两个等长列表并将每对的最大值附加到新列表的更简单/首选方法

2025年05月04日11luoye11

给定两个等长的列表,是否有更简单或更喜欢的方法来迭代两个等长的列表并将每对元素的最大值附加到新列表?这是我知道的两种方法。

import itertools 
 
a = [1,2,3,4,5] 
b = [1,1,6,3,8] 
m1 = list() 
m2 = list() 
 
for x, y in zip(a, b): 
    m1.append(max(x, y)) 
 
for x in itertools.imap(max, a, b): 
    m2.append(x) 

这两个结果都是 [1, 2, 6, 4, 8],这是正确的。有没有更好的办法?

请您参考如下方法:

map(max, a, b) 
[max(x, y) for x, y in zip(a, b)]