python - 如何从多个列表中找到最大值?

标签 python performance list numpy max

我有多个相同大小的列表(或 numpy 数组),我想返回一个相同大小的数组,每个点都有最大值。

例如,

A = [[0,1,0,0,3,0],[1,0,0,2,0,3]]
B = [[1,0,0,0,0,4],[0,5,6,0,1,1]]
C = numpy.zeros_like(A)
for i in xrange(len(A)):
    for j in xrange(len(A[0])):
        C[i][j] = max(A[i][j],B[i][j])

结果是 C = [[1,1,0,0,3,4],[1,5,6,2,1,3]]

这工作正常,但效率不高 - 特别是对于我拥有的数组大小和我需要比较的数组数量。我怎样才能更有效地做到这一点?

最佳答案

使用numpy.maximum :

numpy.maximum(x1, x2[, out])
Element-wise maximum of array elements.

Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a nan, then that element is returned. If both elements are nans then the first is returned. The latter distinction is important for complex nans, which are defined as at least one of the real or imaginary parts being a nan. The net effect is that nans are propagated.

关于python - 如何从多个列表中找到最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10129561/

相关文章:

python - 如何计算列表中每三个值的平均值

python - 为什么添加到列表的前面需要二次时间?

python - Python生态系统中是否有与C++编译器优化等效或类似的机制?

python - 如何在 Django 1.8 中使用 jinja2 作为模板引擎

从两个选项中获取一个强制参数的 Python 函数

python - 如何快速比较列表和集合?

php - 如果A表查找结果为零,如何查找B表?

Python 列表中浮点的成员资格

java - MySQL - 一个字段中的多个值或多对多关系?

C++: Scott Meyers "Effective STL": item 31: know your sorting options: 帮助理解