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