Arman Mojaver
Arman Mojaver

Reputation: 451

Split list based on condition in Python

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.

Upvotes: 3

Views: 832

Answers (1)

Rakesh
Rakesh

Reputation: 82765

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]]

Upvotes: 6

Related Questions