This is the input list in witch every elemente of the list contain one string of only 0 or 1:
input = ['00001001010', '1010100000100', '10100010010001']
I would like to create to transform this list, in a list of lists, where each one of the sublists contain for each element each figure(converted in intager) previously contained in the string element of the starting list.
therefore i would have as a return:
output = [[0,0,0,0,1,0,0,1,0,1,0], [1,0,1,0,1,0,0,0,0,0,1,0,0], [1,0,1,0,0,0,1,0,0,1,0,0,0,1]]
I tryed all kind of lists comprehension, but i ended up with some computational expensive code for problem like that, especially because my program receives in input lists of this type but fifty times longer . Surely there is an optimal way to do it but I can't find it. Any of you have an idea? Maybe there is a way to take advantage of the fact that strings can only contain characters 0 and 1.
CodePudding user response:
You can use map(int, list)
:
(don't use built-in function
as variable (here you use input
as variable, If you write input()
you get an error))
>>> lst = ['00001001010', '1010100000100', '10100010010001']
>>> output = [list(map(int,l)) for l in lst]
>>> output
[[0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1]]
CodePudding user response:
Try this way -
inlist = ['00001001010', '1010100000100', '10100010010001']
outlist = [[int(c) for c in st] for st in inlist]
print(outlist)
The outer list comprehension will loop over each string (denoted by st
). The inner list comprehension just loop over each character of that string (st
) and turns them into integer.