查找两个列表的索引最大值



假设我有 2 个列表:

L1 = [2,4,1,6]
L2 = [1,5,2,3]

输出应该是一个新列表,其中包含根据位置在 L1 或 L2 中找到的最大数字。

示例输出:

L3 = [2, 5, 2, 6]

怎么办?

一种可能的解决方案是压缩列表,然后按元素应用最大操作,这可以通过调用函数map在 python 中获得

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

或通过列表推导更 pythonic

L3 = [max(l1, l2) for l1, l2 in zip(L1, L2)]

或使用开箱操作的更短版本

L3 = [max(*l) for l in zip(L1, L2)]

您可以在列表推导中使用zip()max()

>>> L1 = [2,4,1,6]
>>> L2 = [1,5,2,3]
>>> [*map(max, zip(L1, L2))]
[2, 5, 2, 6]

如果你可以使用numpy,使用numpy.maximum() ufunc非常简单:

>>> 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)

最新更新