Reputation: 49
I am trying to convert a multi digit string in sublists, into sublists of single digit integers. I would like to achieve this using simple list comprehension.
Original list:
# [[], ['0000000'], ['2200220'], ['2222220'], ['2200220'], ['2000020'], []]
Goal List:
# [[0, 0, 0, 0, 0, 0, 0], [2, 2, 0, 0, 2, 2, 0], [2, 2, 2, 2, 2, 2, 0], [2, 2, 0, 0, 2, 2, 0], [2, 0, 0, 0, 0, 2, 0]]
The following thread helped me get this far. List of list, converting all strings to int, Python 3
If I use this nested list comprehension, the strings turn into a single integer.
mylist = [[int(i) for i in s] for s in mylist]
# [[], [0], [2200220], [2222220], [2200220], [2000020], []]
I was able to do what I wanted by using two steps that involved importing a module, but this is not ideal.
import itertools
mylist = list(itertools.chain.from_iterable(mylist))
# ['0000000', '2200220', '2222220', '2200220', '2000020']
mylist_two = [[int(i) for i in str(s)] for s in mylist]
# [[0, 0, 0, 0, 0, 0, 0], [2, 2, 0, 0, 2, 2, 0], [2, 2, 2, 2, 2, 2, 0], [2, 2, 0, 0, 2, 2, 0], [2, 0, 0, 0, 0, 2, 0]]
Could anyone point me in the right direction? Thank you.
Upvotes: 0
Views: 479
Reputation: 11183
Slight different way, given that each sublist contains just one element:
mylist = [[], ['0000000'], ['2200220'], ['2222220'], ['2200220'], ['2000020'], []]
[ [ int(ch) for ch in e[0] ] for e in mylist if len(e) > 0 ]
#=> [[0, 0, 0, 0, 0, 0, 0], [2, 2, 0, 0, 2, 2, 0], [2, 2, 2, 2, 2, 2, 0], [2, 2, 0, 0, 2, 2, 0], [2, 0, 0, 0, 0, 2, 0]]
Upvotes: 0
Reputation: 43504
A simple way is to flatten the list using a nested list comprehension, then convert each character in the string to integer.
Here's how you can modify your code:
mylist = [[], ['0000000'], ['2200220'], ['2222220'], ['2200220'], ['2000020'], []]
print([[int(z) for z in y] for x in mylist for y in x])
#[[0, 0, 0, 0, 0, 0, 0],
# [2, 2, 0, 0, 2, 2, 0],
# [2, 2, 2, 2, 2, 2, 0],
# [2, 2, 0, 0, 2, 2, 0],
# [2, 0, 0, 0, 0, 2, 0]]
Upvotes: 2
Reputation: 24232
You can simply do:
data = [[], ['0000000'], ['2200220'], ['2222220'], ['2200220'], ['2000020'], []]
out = [list(map(int, list(s[0]))) for s in data if s ]
print(out)
# [[0, 0, 0, 0, 0, 0, 0], [2, 2, 0, 0, 2, 2, 0], [2, 2, 2, 2, 2, 2, 0], [2, 2, 0, 0, 2, 2, 0], [2, 0, 0, 0, 0, 2, 0]]out = [list(s[0]) for s in data if s ]
Since strings are iterable, list('123')
will create a list by iterating on the individual characters of '123', so it will return ['1', '2', '3']
. We then map each individual digit to an integer.
Upvotes: 1