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

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]]
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
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())
Filipp Voronov
  • 4,077
  • 5
  • 25
  • 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
  • 2,221
  • 1
  • 24
  • 23