I currently have a string
x = ([15, 16, 17, 18, 19, 20, 21, 22, 23], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
. My goal is to convert this entire string into two lists, capturing each numerical value within the list as its own item. x.split(",")
returns ['([15', ' 16', ' 17', ' 18', ' 19', ' 20', ' 21', ' 22', ' 23']
and "".join(x)
returns '([15 16 17 18 19 20 21 22 23'
- neither of which are the result I am looking for. The end result should be two lists, with each number in the list an individual item in numerical format. Does anyone know the best way to accomplish this in python?
Asked
Active
Viewed 68 times
0

E. Lutins
- 115
- 2
- 11
-
`import ast` and then `ast.literal_eval(x)` will give you a tuple of two lists. – ayhan Jun 13 '18 at 15:42
3 Answers
0
Using json:
import json
x = '([15, 16, 17, 18, 19, 20, 21, 22, 23], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])'
json.loads(x.replace('(','[').replace(')',']'))

Anton vBR
- 18,287
- 5
- 40
- 46
0
>>> first, second = ast.literal_eval('''x = ([15, 16, 17, 18, 19, 20, 21, 22, 23], \
... [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])'''[4:])
>>> first
[15, 16, 17, 18, 19, 20, 21, 22, 23]
>>> second
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358
0
Use ast.literal_eval
:
import ast
x = '([15, 16, 17, 18, 19, 20, 21, 22, 23], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])'
x = ast.literal_eval(x)
lst1, lst2 = x[0], x[1]
print(lst1) # [15, 16, 17, 18, 19, 20, 21, 22, 23]
print(lst2) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Austin
- 25,759
- 4
- 25
- 48