假设我有两个列表:
L1 = [2,4,1,6]
L2 = [1,5,2,3]
输出应该是一个新的列表,其中包含根据它们的位置在L1或L2中找到的最大数。
示例输出:
L3 = [2, 5, 2, 6]
如何做到?
其中一种可能的解决方案是将列表压缩,然后逐个元素地应用最大操作,这可以通过在Python中调用函数 map
来实现。
L1 = [2,4,1,6]
L2 = [1,5,2,3]
L3 = map(max, zip(L1, L2)) # python2
L3 = list(map(max, zip(L1, L2))) # python3
或者通过列表推导式使其更具Python风格
L3 = [max(l1, l2) for l1, l2 in zip(L1, L2)]
或者更短的版本使用解包操作
L3 = [max(*l) for l in zip(L1, L2)]
>>> L1 = [2,4,1,6]
>>> L2 = [1,5,2,3]
>>> [*map(max, zip(L1, L2))]
[2, 5, 2, 6]
numpy
,那么使用numpy.maximum()
函数非常简单:>>> import numpy as np
>>> arr1 = np.array([2, 4, 1, 6])
>>> arr2 = np.array([1, 5, 2, 3])
>>> np.maximum(arr1, arr2)
array([2, 5, 2, 6])
list_a = [2,4,1,6]
list_b = [1,5,2,3]
max_list = [value if list_b[index]<value else list_b[index] for index, value in enumerate(list_a)]
print(max_list)
[2, 5, 2, 6]
a, b = [10,20,30], [11,2,40]
c = [x if x > y else y for x, y in zip(a, b)]
print(c)
输出:[11,20,40]
l=[1,2,7]
m=[4,5,6]
max=[(l[i] if l[i]>m[i] else m[i] ) for i in range(0,len(l))]
print(max)
max()
函数,您只需要一行代码就可以得到解决方案。 - Martijn Pieters