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 Answers3

3

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]]
Andriy Ivaneyko
  • 18,421
  • 4
  • 52
  • 73
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())
Philip Voronov
  • 3,947
  • 5
  • 22
  • 32
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]]
funk
  • 1,921
  • 1
  • 21
  • 22