Reputation: 3
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?
Upvotes: 0
Views: 62
Reputation: 118021
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')
Upvotes: 2