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]]]
3
  • 2
    You can execute code with eval e.g. a = eval('[[4,2],[8,5]]') Commented Mar 11, 2021 at 13:35
  • This is a duplicate question: check this. stackoverflow.com/questions/25572247/… Commented Mar 11, 2021 at 13:38
  • 1
    Question has actually nothing to do with machine-learning or neural-network - kindly do not spam irrelevant tags (removed). Commented Mar 11, 2021 at 13:46

2 Answers 2

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))

Sign up to request clarification or add additional context in comments.

3 Comments

Notice that in OP's question the list expression is actually a string; it is '[[4,2],[8,5]]', not [[4,2],[8,5]].
ooops......then we can use string.split() method on '[[4,2],[8,5]]' to convert to string. can we?
Well, why don't you try it? :)
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))

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.