-1

I have a list of strings like this:

L=['[1,2,3]','[3,4,5,6]','[9,8,7]']

I want to make a list of list elements like this:

Y=[[1,2,3],[3,4,5,6],[9,8,7]]

How can I do it in python?

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218

3 Answers3

2

You can use ast.literal_eval to evaluate each string as a python literal within a list comprehension

>>> from ast import literal_eval
>>> [literal_eval(i) for i in L]
[[1, 2, 3], [3, 4, 5, 6], [9, 8, 7]]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

Every element of your array is a valid JSON so you could do

import json

Y = [json.loads(l) for l in L]
Ursus
  • 29,643
  • 3
  • 33
  • 50
1

You could also do this manually:

>>> L=['[1,2,3]','[3,4,5,6]','[9,8,7]'] 
>>> [[int(x) for x in l[1:-1].split(',')] for l in L]
[[1, 2, 3], [3, 4, 5, 6], [9, 8, 7]]

Or without split(), as suggested by @Moinuddin Quadri in the comments:

>>> [[int(x) for x in l[1:-1:2]] for l in L]
[[1, 2, 3], [3, 4, 5, 6], [9, 8, 7]]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75