Ibrahim
Ibrahim

Reputation: 175

Split list of tuples into seprate list based on a condition

I have a list of tuple like this:

a = [(1, 0.0), (1, 1.0), (1, 0.0), (2, 0.36034115138592754), (1, 1.0),
(1, 0.0), (2, 0.0), (3, 0.9999999999999991), (4, 0.0), (5, 0.0), 
(6, -1.0000000000000002), (7, 0.9999999999999999), (8, 1.0000000000000002), (9, 1.0), 
(10, 0.0), (1, 1.0), (1, 0.0)]

I would like to split it every time the first element is 1. I have tried with the groupby, but I need to have a different list of tuple every time because later I have to plot it and each of these tuple is a specific point. My expected output would be:

[(1, 0.0)]
[(1, 1.0)]
[(1, 0.0), (2, 0.36034115138592754)]
[(1, 1.0)]
[(1, 0.0), (2, 0.0), (3, 0.9999999999999991), (4, 0.0), (5, 0.0), 
(6, -1.0000000000000002), (7, 0.9999999999999999), (8, 1.0000000000000002), (9, 1.0), (10, 0.0)]
[(1, 1.0)]
[(1, 0.0)]

Upvotes: 0

Views: 159

Answers (1)

Ibrahim
Ibrahim

Reputation: 175

I here post the solution of @Mustafa Aydin so that other users can find the solution soon.

inds, = np.nonzero(np.array(a)[:, 0] == 1)
[sub.tolist() for sub in np.split(a, inds) if sub.size]

Upvotes: 1

Related Questions