import ast
print ast.literal_eval([y for x in list_ for y in x][0])
How to convert malformed list into a list of int in python [closed]
Question
Here is my list; an output from a database entered as string:
list_=(('[96, 71, 16, 81, 21, 56, 91]',),)
My goal is to convert it into a list of ints: [96, 71, 16, 81, 21, 56, 91]
My attempt:
import ast
print ast.literal_eval(list_[0][0])
The expected output
Output:[96, 71, 16, 81, 21, 56, 91]
However, the solution is not compatible with some of the output
list_[0][0]
results in an error: out of range.
Any suggestions on other possible methods to solving the problem? Thanks.
Solution
OTHER TIPS
while type(list_) is not str:
try:
list_ = list_[0]
except IndexError:
break
Now list_
is the string you want.
Have you tried this:
from numpy import fromstring
fromstring(list_[0][0][1:(len(list_[0][0])-1)], sep=',', dtype='int32').tolist()
And just for fun, a generic untangler
from collections import Iterable
def untangle(thing):
stack = [thing]
result = []
while stack:
current = stack.pop()
if isinstance(current, basestring):
if current[-1] == ']':
current = current[1:-1]
for x in current.strip().split(','):
result.append(int(x.strip()))
elif isinstance(current, Iterable):
stack.extend(reversed(current))
else:
print "dont know what do do with", repr(current)
return result
untangle((('[96, 71, 16, 81, 21, 56, 91]',),))
[96, 71, 16, 81, 21, 56, 91]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow