【发布时间】:2020-07-14 19:08:48
【问题描述】:
在 python 中迭代二维数组的最快方法是什么?考虑到我总是需要 x 和 y 索引。
例如,我有这段代码试图“匹配”矩阵中相同数字的 3 个,如果它们是数字 2、3、4、5 或 6:
for x in range(matrix.shape[0]):
for y in range(matrix.shape[1]):
if matrix[x][y] == 2 or matrix[x][y] == 3 or matrix[x][y] == 4 or matrix[x][y] == 5 or matrix[x][y] == 6: ## if i find one of the numbers i need
fuseNumber = matrix[x][y] ## lets get that number
if matrix[x+1][y] == fuseNumber: ## if we find another of that to the bottom of the initial one, we should try to find a third one
if matrix[x-1][y] == fuseNumber: ## if we find another one at the top from the initial one
matrix[x][y] = 0
matrix[x+1][y] = 0
matrix[x-1][y] = 0
...
代码将继续使用一些 if,就像这个一样,以确保它测试所有可能的组合,但这并不重要。 我尝试将其更改为:
it = numpy.nditer(matrix, flags=['multi_index'])
while not it.finished:
x = it.multi_index[0]
y = it.multi_index[1]
if matrix[x][y] == 2 or matrix[x][y] == 3 or matrix[x][y] == 4 or matrix[x][y] == 5 or matrix[x][y] == 6:
fuseNumber = matrix[x][y] ## lets get that fuse number, whichever it may be!
if matrix[x+1][y] == fuseNumber: ## if we find another of that to the bottom of the initial one, we should try to find a third one
if matrix[x-1][y] == fuseNumber: ## if we find another one at the top from the initial one /////// center bottom top
matrix[x][y] = 0
matrix[x+1][y] = 0
matrix[x-1][y] = 0
...
it.iternext()
但是使用 timeit.timeit() 它向我展示了第二个代码实际上更慢。尽管有这两个示例,但您将如何编写相同的代码,但获得最佳性能?
谢谢!
【问题讨论】:
-
nditer不是更快的迭代器,至少在 Python 级别使用时不是。只有在编译代码中使用它才有帮助。在 Python 代码中没有更快的方法来迭代数组。在列表上迭代更快。要获得最佳的numpy速度,您应该使用快速编译的numpy方法,而不是迭代。 -
您上一个问题的答案有什么问题? stackoverflow.com/questions/60993647/…。我很想将此标记为重复。
-
@hpaulj 没什么,真的,这只是一个不同的问题,因为现在我需要更多地控制索引,它实际上是另一种方法,但我承认这个问题看起来一样哈哈
标签: python python-3.x numpy multidimensional-array numpy-ndarray