python - 在 n 个不相等的列表中找到最大值

标签 python list

我有 n 个列表。

data = [
    [1, 2, 3, 4, 5, 6, 7, 8],
    [2, 6, 3, 5, 9, 1, 1, 1, 2, 4, 5],
    [8, 1, 4, 1, 2, 3, 4, 2, 5]
    [3, 9, 1, 2, 2, 1, 1, 5, 9, 3]
]

我怎样才能有效地比较它们并生成一个始终包含当前位置最高值的列表? 我不知道该怎么做,因为每个列表的边界都不同。

上面示例的输出应该是一个包含这些值的列表:

[8,9,4,5,9,6,7,8,9,4,5]

最佳答案

最惯用的方法是转置 2D 列表并在转置列表的每一行上调用 max。但在您的情况下,您正在处理参差不齐的列表,因此不能在此处直接应用zip(它仅压缩到最短的列表)。

相反,使用 itertools.zip_longest(izip_longest 用于 python 2),然后使用 map 应用 max -

from itertools import zip_longest
r = list(map(max, zip_longest(*data, fillvalue=-float('inf'))))

或者,使用 @Peter DeGlopper's suggestion , 具有列表理解 -

r = [max(x) for x in zip_longest(*data, fillvalue=-float('inf'))]

print(r)
[8, 9, 4, 5, 9, 6, 7, 8, 9, 4, 5]

在这里,我使用 fillvalue 参数用负无穷大填充缺失值。中间结果看起来像这样 -

list(zip_longest(*data, fillvalue=-float('inf')))

[(1, 2, 8, 3),
 (2, 6, 1, 9),
 (3, 3, 4, 1),
 (4, 5, 1, 2),
 (5, 9, 2, 2),
 (6, 1, 3, 1),
 (7, 1, 4, 1),
 (8, 1, 2, 5),
 (-inf, 2, 5, 9),
 (-inf, 4, -inf, 3),
 (-inf, 5, -inf, -inf)]

现在,应用 max 变得简单明了 - 只需对每一行执行此操作即可。

关于python - 在 n 个不相等的列表中找到最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48156643/

相关文章:

java - 如何将 Set<Class<?>> 转换为列表?

python - 属性错误 : 'History' object has no attribute 'predict' - Fitting a List of train and test data

java - 创建单独的类的替代方法

python - 如何在Pytorch中形成一个连续的数字序列?

python - Python 中浮点到整数的转换速度更快

python - 关于余弦相似度,损失函数和网络如何选择(我有两个方案)

python - pandas dataframe hexbin 图没有 xlabel 或轴值

java - Java 中的 'ambiguous type' 错误是什么?

python - 使用循环更改二维列表中的多个值

python - 为什么 numpy 的广播有时允许比较不同长度的数组?