2

I am trying to take two dimensional array input in python which can have n number of Rows and Columns. What I have tried is

x =  raw_input()[2:-2].split(',')

My input is following

[[1,2,3,4],[5,1,2,3],[9,5,1,2]]

What output I am getting output

['1', '2', '3', '4]', '[5', '1', '2', '3]', '[9', '5', '1', '2']

I want to get array as same as my input.

3 Answers 3

4

Use ast.literal_eval is designed for this goal ( it's safe), see usage in code sample below:

import ast

s = '[[1,2,3,4],[5,1,2,3],[9,5,1,2]]'
ast.literal_eval(s)
# [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Sign up to request clarification or add additional context in comments.

Comments

1
exec('x=' + raw_input())
#in x is now what you wanted, [[1,2,3,4],[5,1,2,3],[9,5,1,2]]

or more safe:

import ast
x = ast.literal_eval(raw_input())

2 Comments

Thank you.. Worked Perfectly
The exec is something you have to avoid. Please see stackoverflow.com/questions/1933451/…
0

Please check an older answer on this:

https://stackoverflow.com/a/21163749/2194843

$ cat /tmp/test.py

import sys, ast
inputList = ast.literal_eval(sys.argv[1])
print(type(inputList))
print(inputList)

$ python3  /tmp/test.py '[[1,2,3,4],[5,1,2,3],[9,5,1,2]]'

<class 'list'>
[[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]

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.