Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string that looks like a list into a real list - python

My input files have lines that looks like this:

[(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]
[(0, 1, 6), (1, 3,7), (3, 1,4), (3, 1,3), (8, 1,2)]
[1,2,3,5,3]

There are no letters, no decimals, only integers and number of element in tuples will be consistent.

How do i make them into real list of tuples / list of int?

like image 388
alvas Avatar asked Nov 27 '13 18:11

alvas


1 Answers

Python comes with batteries included - that problem is solved by ast.literal_eval():

>>> import ast
>>> ast.literal_eval("[(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]")
[(0, 1), (1, 3), (2, 1), (3, 1), (4, 1)]
>>> ast.literal_eval("[(0, 1, 6), (1, 3,7), (3, 1,4), (3, 1,3), (8, 1,2)]")
[(0, 1, 6), (1, 3, 7), (3, 1, 4), (3, 1, 3), (8, 1, 2)]
>>> ast.literal_eval("[1,2,3,5,3]")
[1, 2, 3, 5, 3]
like image 162
Tim Pietzcker Avatar answered Oct 14 '22 16:10

Tim Pietzcker