1

I need to convert the following string that I pass as a command-line argument in my python program

'[[0,1,0],[1,1,1],[0,1,0]]'. Numpy has something that could be useful for my problem, however, it works only with 1D arrays found in a string. ,

https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html

Which options there are to solve my problem?

Roger Almengor
  • 442
  • 5
  • 16

1 Answers1

2

I find one way to solve your problem. You can replace your string and remove '[' or ']'. Then you can convert to 1D array and finally reshape to 2D array.

Code:

import numpy as np

string=string.replace('[','')
string=string.replace(']','')

array1d=np.fromstring(string,dtype=int,sep=',')
array2d=np.reshape(array1d, (-1, 3))

I hope this is help you. Have a good day!

Lucas Lyon
  • 36
  • 3