Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list based on condition in Python

Tags:

python

list

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.

like image 344
Arman Mojaver Avatar asked Jun 28 '26 16:06

Arman Mojaver


1 Answers

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]]
like image 161
Rakesh Avatar answered Jun 30 '26 05:06

Rakesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!