0

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?

1 Answer 1

2

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.