0

I have a text file with data in the following format:

['[10,2,3,4]','[5,26,17,28]','[10,13,36,48]']

How do I convert this to:

[[10,2,3,4],[5,26,17,28],[10,13,36,48]] ?

Which I think would be converting a list of str to a list of lists of int. I have tried using all suggested methods such as list comprehensions, map etc, but either end up with each individual integer as a str e.g. 48 as '4','8',... or stays exactly the same. I am using Python 3.4

user1478335
  • 1,769
  • 5
  • 25
  • 37
  • possible duplicate of [convert string representation of list to list in python](http://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list-in-python) – Mazdak Jun 17 '15 at 19:32

1 Answers1

2

You could use ast.literal_eval to evaluate those strings to actual lists.

>>> import ast
>>> lst = ['[10,2,3,4]','[5,26,17,28]','[10,13,36,48]']
>>> [ast.literal_eval(s) for s in lst]
[[10, 2, 3, 4], [5, 26, 17, 28], [10, 13, 36, 48]]

This is similar to evaluating the lists, except that literal_eval, as the name suggests, will only evaluate Python literals, which makes it much safer than the builtin eval.

tobias_k
  • 81,265
  • 12
  • 120
  • 179