Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list of tuples based on value within tuple

Tags:

python

If I have the following:

[(1,2),(2,3),(0,0),(4,0),(0,1),(3,9),(2,0),(2,4)]

How can I split it into:

[(1,2),(2,3)], [(0,1),(3,9)], [(2,4),]

were every time I see a tuple with a 0 at index 1, e.g. (1,0), I split the list.

like image 304
Baz Avatar asked Dec 10 '25 13:12

Baz


1 Answers

Try this:

from itertools import groupby

x = [(1,2), (2,3), (0,0), (4,0), (0,1), (3,9), (2,0), (2,4)]

print [l for l in [list(group) for key, group in groupby(x, key=lambda k: k[1]==0)]
             if l[0][1] != 0]

[OUT] [[(1,2), (2,3)], [(0,1), (3,9)], [(2,4)]]

It produces a list that you can iterate over to get those sublists.

like image 59
BenTrofatter Avatar answered Dec 13 '25 16:12

BenTrofatter



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!