-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
  • 98,167
  • 13
  • 130
  • 181

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
  • 98,167
  • 13
  • 130
  • 181
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
  • 27,319
  • 3
  • 23
  • 42
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
  • 23,173
  • 5
  • 28
  • 59