I don't know how to convert string to list inside of list. Split method seems the most popular, but it doesn't work.
I have a list:
corpus = ['[(0, 1), (1, 2), (2, 1)]']
I want to convert string to list like that:
corpus = [[(0, 1), (1, 2), (2, 1)]]
How I can do it?
CodePudding user response:
Use ast.literal_eval
, a safer alternative to eval
:
import ast
corpus = ['[(0, 1), (1, 2), (2, 1)]']
corpus = [ast.literal_eval(item) for item in corpus]
print(corpus)
# [[(0, 1), (1, 2), (2, 1)]]
CodePudding user response:
Hi I think this simple code will help.
import re
corpus = ['[(0, 1), (1, 2), (2, 1)]']
corpus[0] = re.findall(r'\(\d, \d\)', corpus[0])
temp_lst1 = []
for i in corpus[0]:
temp_lst2 = []
for j in i:
try:
if type(int(j)) == int:
temp_lst2.append(int(j))
except ValueError:
pass
temp_lst1.append(tuple(temp_lst2))
corpus[0] = temp_lst1
print(corpus)