简体   繁体   English

如何迭代矩阵的列?

[英]How to iterate over columns of a matrix?

In python if a define: 在python中如果定义:

a = arange(9).reshape(3,3)

as a 3x3 matrix and iterate: 作为3x3矩阵并迭代:

for i in a:

It'll iterate over the matrix's rows. 它将迭代矩阵的行。 Is there any way to iterate over columns? 有没有办法迭代列?

How about 怎么样

for i in a.transpose():

or, shorter: 或者,更短:

for i in a.T:

This may look expensive but is in fact very cheap (it returns a view onto the same data, but with the shape and stride attributes permuted). 这可能看起来很昂贵,但实际上非常便宜(它将视图返回到相同的数据上,但其形状和步幅属性被置换)。

Assuming that a is a well formed matrix, you could try something like: 假设a是一个格式良好的矩阵,您可以尝试以下方法:

b = zip(*a)
for index in b:
   ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM