在Python中遍历多维数组

2024-03-29 08:51:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python创建了一个多维数组,如下所示:

self.cells = np.empty((r,c),dtype=np.object)

现在我想遍历二维数组的所有元素,而不关心顺序。我怎样才能做到这一点?


Tags: self元素object顺序np数组emptydtype
3条回答

如果需要更改单个单元格的值,则ndnumerate(以numpy为单位)是您的朋友。即使你不这样做,它可能仍然是!

for index,value in ndenumerate( self.cells ):
    do_something( value )
    self.cells[index] = new_value

很明显你在用核弹。有了numpy你就可以做到:

for cell in self.cells.flat:
    do_somethin(cell)

只需遍历一个维度,然后遍历另一个维度。

for row in self.cells:
    for cell in row:
        do_something(cell)

当然,在只有两个维度的情况下,可以使用list comprehension或生成器表达式将其压缩为单个循环,但这不是非常可伸缩或可读的:

for cell in (cell for row in self.cells for cell in row):
    do_something(cell)

如果您需要将其扩展到多个维度,并且确实需要一个平面列表,则可以write a ^{} function

相关问题 更多 >