0

Consider the following code:

array = np.array2string(np.arange(27).reshape(3,3,3))

This creates a numpy array with 3D dimension. The output will look like this:

[[[ 0  1  2]
  [ 3  4  5]
  [ 6  7  8]]

 [[ 9 10 11]
  [12 13 14]
  [15 16 17]]

 [[18 19 20]
  [21 22 23]
  [24 25 26]]]

I want to convert this numpy array to a python list where each index corresponds to a line in the numpy array. It is important to note that there is a whitespace between each number. So the output would look like this:

    Index Type Size  Value 
    0     str    5   0 1 2 
    1     str    5   3 4 5
    2     str    5   6 7 8 
    3     str    5   9 10 11
....
.... and so on

How would I code this?

2
  • 1
    What Size 5 is supposed to mean? Commented Jan 17, 2022 at 19:43
  • It is the size of the string. For instance, if you have a string "1 2" the size is 3 and "Hello" has the size 5. Commented Jan 17, 2022 at 19:48

1 Answer 1

1

You can do this with a sderies of substitutions:

my_array = np.array2string(np.arange(27).reshape(3,3,3))
# remove brackets
my_array = my_array.replace('[', '').replace(']', '').split('\n')
# remove space at the beginning of each line
my_array = [line.lstrip() for line in my_array]
# keep only strings that are not empty
my_array = [line for line in my_array if line]

Result:

['0  1  2',
 '3  4  5',
 '6  7  8',
 '9 10 11',
 '12 13 14',
 '15 16 17',
 '18 19 20',
 '21 22 23',
 '24 25 26']
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.