python split a string of tuples into a list of lists

Solutions on MaxInterview for python split a string of tuples into a list of lists by the best coders in the world

showing results for - "python split a string of tuples into a list of lists"
Declan
28 Feb 2019
1# Basic syntax:
2import ast
3[list(elem) for elem in ast.literal_eval(your_string)]
4
5# Example usage:
6# Say you want to convert a string like:
7'(0,0,0), (0,0,1), (1,1,0)' # or like
8'((0,0,0), (0,0,1), (1,1,0))'
9# to a list of lists like:
10[[0, 0, 0], [0, 0, 1], [1, 1, 0]]
11
12# Import the Abstract Syntax Trees package:
13import ast
14your_string = '(0,0,0), (0,0,1), (1,1,0)'
15
16# First, convert to tuple of tuples:
17your_tuple = ast.literal_eval(your_string)
18print(your_tuple)
19--> ((0,0,0), (0,0,1), (1,1,0))
20
21# Then, convert to a list of lists with list comprehension:
22your_list = [list(elem) for elem in your_tuple]
23print(your_list)
24--> [[0, 0, 0], [0, 0, 1], [1, 1, 0]]