简体   繁体   中英

Python iterate through a multidimensional numpy array in different ways

For Example I have a numpy array A in this form:

A = [["a", "b", "c"], 
     ["d", "e", "f"],
     ["g", "h", "i"]]

Now I want to iterate through this Array.
First I want the output be a list or numpy array like this. So iterate line by line:

O = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

Then iterate by column:

O = ["a", "d", "g", "b", "e", "h", "c", "f", "i"]

Then iterate backwards line by line:

O = ["i", "h", "g", "f", "e", "d", "c", "b", "a"]

And last backwards column by column:

O = ["i", "f", "c", "h", "e", "b", "g", "d", "a"]

So I know how to do this all with two for loops but is there a way you can do this with a numpy function and only one for loop or just numpy functions?

This is trivial to do with numpy using flatten and transpose as needed

>>> import numpy as np
>>> A = np.array([["a", "b", "c"], 
                  ["d", "e", "f"],
                  ["g", "h", "i"]])
>>> A.flatten()
array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], dtype='<U1')
>>> A.T.flatten()
array(['a', 'd', 'g', 'b', 'e', 'h', 'c', 'f', 'i'], dtype='<U1')
>>> A.flatten()[::-1]
array(['i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'], dtype='<U1')
>>> A.T.flatten()[::-1]
array(['i', 'f', 'c', 'h', 'e', 'b', 'g', 'd', 'a'], dtype='<U1')

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