简体   繁体   中英

How to iterate over columns of a matrix?

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 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:
   ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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