Issue
I have a list of elements which internally is separated by 0s. The format is like that:
[0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]
I would like to use the zeros as separators and split it into sublists. In that example its:
[[], [2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]
The zeros will therefore disappear. A leading zero or an ending zero should make an empty list at the beginning or the end.
Until know, I do that in an ugly way by joining the list together to a string, then split it and make a list of it again.
Is there a fancy pythonic way to do that easier?
Solution
You could use a groupby approach:
from itertools import groupby
k = [0, 2, 2, 0, 1, 5, 5, 3, 1, 3, 0, 7, 4, 6, 7, 4, 6]
gr = groupby(k, lambda a: a==0)
l = [[] if a else [*b] for a,b in gr]
print(l)
Output:
[[], [2, 2], [], [1, 5, 5, 3, 1, 3], [], [7, 4, 6, 7, 4, 6]]
You can fix the internal [] by:
l = [ a for idx,a in enumerate(l) if idx in (0,len(l)) or a]
to get
[[], [2, 2], [1, 5, 5, 3, 1, 3], [7, 4, 6, 7, 4, 6]]
You can substitute the list comp by
l = []
for a,b in gr:
if a:
l.append([])
else:
l.append([*b])
Answered By - Patrick Artner
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.