0

a python string:

'[[4,2],[8,5]]'

for example, where you have a fairly complex multidimensional array of information, maybe is extracted from a file or user input and is naturally a string. How should I go about turning this into an actual array. I want a general implementation so that I can perform this to any multidimensional and complex array. This is for a machine learning project, and any of these arrays can be represented with a shape (e.g. (3,2,5) ) and a list of its corresponding values (e.g. [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0] ) such that is may look like:

[[[1,2,3,4,5],
  [6,7,8,9,0]],
 [[1,2,3,4,5],
  [6,7,8,9,0]],
 [[1,2,3,4,5],
  [6,7,8,9,0]]]
desertnaut
  • 57,590
  • 26
  • 140
  • 166
  • 2
    You can execute code with `eval` e.g. `a = eval('[[4,2],[8,5]]')` – tomjn Mar 11 '21 at 13:35
  • This is a duplicate question: check this. https://stackoverflow.com/questions/25572247/how-to-convert-array-string-to-an-array-in-python – kabooya Mar 11 '21 at 13:38
  • 1
    Question has actually nothing to do with `machine-learning` or `neural-network` - kindly do not spam irrelevant tags (removed). – desertnaut Mar 11 '21 at 13:46

2 Answers2

0

try this:

def flatten_list(_2d_list):
    flat_list = []
    for element in _2d_list:
        if type(element) is list:
            for item in element:
                flat_list.append(item)
        else:
            flat_list.append(element)
    return flat_list

nested_list = [[4,2],[8,5]]

print(nested_list)
print(flatten_list(nested_list))

ullas kunder
  • 384
  • 4
  • 11
0
import numpy as np
list = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]
array = np.array(list)
array = np.reshape(array, (3,2,5))
Alex97
  • 73
  • 2
  • 9