开发者

How to iterate over columns of a matrix?

开发者 https://www.devze.com 2023-02-21 17:15 出处:网络
In python if a define: a = arange(9).reshape(3,3) as a 3x3 matrix and iterate: for i in a: It\'ll iterate over the matrix\'s rows. Is there any way to iterate 开发者_JAVA百科over columns?How abo

In python if a define:

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

as a 3x3 matrix and iterate:

for i in a:

It'll iterate over the matrix's rows. Is there any way to iterate 开发者_JAVA百科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:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号