0

I'm need to pass a 2D list to my program via the command line like the following:

python myscript.py [[int,int,int],[int,int,int]]

I'm getting the run time param via sys.argv[1], but its interpreted as a string. I'm having a hard time converting it into a 2D list object.

  • voted to close my own question...i found the answer here: http://stackoverflow.com/questions/19723911/convert-a-string-2d-list-back-to-2d-list-in-python –  Dec 15 '16 at 17:41

2 Answers2

1

ast.literal_eval is what you need to look at.

In [7]: x = '[[1002763,201608,1],[1002763,201612,2]]'
In [9]: import ast

In [10]: ast.literal_eval(x)
Out[10]: [[1002763, 201608, 1], [1002763, 201612, 2]]

In [11]: ast.literal_eval(x)[1]
Out[11]: [1002763, 201612, 2]

In [12]: ast.literal_eval(x)[1][2]
Out[12]: 2
harshil9968
  • 3,254
  • 1
  • 16
  • 26
0

Simplest way to do this (Assuming that you are giving valid string as a input)

x=sys.argv[1] 

list_2D=[i.split(",") for i in x[2:-2].split("],[")]

print list_2D

Output:

[['1002763', '201608', '1'], ['1002763', '201612', '2']]
Atul Rokade
  • 156
  • 1
  • 4