I have a list like this:
mylist = [2, 3, 4, 0, 0, 0, 6, 7, 8, 0, 4, 9, 0, 2, 0, 2, 0, 20, 0]
and I need to remove the 0's and gather the rest of the numbers that are together as groups.
This is what I have done so far, but the numbers are not split in groups.
mylist = [2, 3, 4, 0, 0, 0, 6, 7, 8, 0, 4, 9, 0, 2, 0, 2, 0, 20, 0]
result = []
indexes = []
for i, j in enumerate(mylist):
if j != 0:
result.append(j)
indexes.append(i)
print(result)
print(indexes)
I don't know how to continue from here.
This is the result that I am looking for:
result = [[2, 3, 4], [6, 7, 8], [4, 9], [2], [2], [20]]
Thank you.
Using itertools.groupby
Ex:
from itertools import groupby
mylist = [2, 3, 4, 0, 0, 0, 6, 7, 8, 0, 4, 9, 0, 2, 0, 2, 0, 20, 0]
result = [list(v) for k, v in groupby(mylist, lambda x: x!=0) if k]
print(result)
Output:
[[2, 3, 4], [6, 7, 8], [4, 9], [2], [2], [20]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With