I know there are similar posts to this topic, however they often focus on the list items being letters and so the outcome often means they are wrapped in double quotes.
However, I am dealing with lists of numbers and I have been unable to find a solution that addresses my need for converting a string representation of a list of numerical lists ...
"[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]"
... into an actual list
of numerical list
s, as I mentioned I am dealing with numerical items for math.
list_string = "[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]"
ini_list = "[" list_string "]"
goal = list(ini_list)
print(goal)
#Desired Outcome:
#goal = [[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]]
CodePudding user response:
A very simple (and safe/robust) approach is to use the ast.literal_evel
function.
In this case, the ast.literal_eval
function is a safe way to evaluate strings and convert them to their intended type, as there is logic in the function to help remove the risk of evaluating malicious code.
Use:
import ast
list_string = "[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]"
result = ast.literal_eval(f'[{list_string}]')
Output:
[[1, 2, 3, 4, 5, 6], [5, 1, 4, 6, 3, 2], [3, 6, 4, 1, 5, 2]]
CodePudding user response:
You can use exec()
function, that executes python code.
>>> exec("a = [[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]]")
>>> a
[[1, 2, 3, 4, 5, 6], [5, 1, 4, 6, 3, 2], [3, 6, 4, 1, 5, 2]]
CodePudding user response:
If you take list(string) you will just split string into chars. For example list('[1, 2]')
= ['[', '1', ',', ' ', '2', ']']
.
But what you have is a string containing a python literal (a piece of code that describes a value). And you need to turn it into actual value. For that there is eval
function. So just do goal = eval(ini_list)
. Hope I helped you.
CodePudding user response:
Here is one faster way to do so using list comprehension and split()
:
list_string = "[1,2,3,4,5,6],[5,1,4,6,3,2],[3,6,4,1,5,2]"
goal = [[int(num) for num in sublist.split(",")] for sublist in list_string[1:-1].split("],[")]
print(goal) # [[1, 2, 3, 4, 5, 6], [5, 1, 4, 6, 3, 2], [3, 6, 4, 1, 5, 2]]
- We separate the string at each
],[
, to retrieve the different sublists. - Then, we separate each sublist at
,
and finally convert the separated numbers to integers.
The alternative with for loops would be:
goal = []
for sublist in list_string[1:-1].split("],["):
new_sublist = []
for num in sublist.split(","):
new_sublist.append(int(num))
goal.append(new_sublist)
print(goal)