Imagine that I have an order list of tuples:
s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)]
Given a parameter X
, I want to select all the tuples that have a first element equal or greater than X
up to but not including the first tuple that has -1 as the second element.
For example, if X = 3
, I want to select the list [(3,0), (4,0)]
One idea I had is: Get the cut-off key with
E = min (x [0] for x in s if (x [0] >= X) and (x [1] == -1) )
Then select elements with keys between the X
and E
:
R = [x for x in s if X <= x [0] < E]
That gives me what I want in R, but it seems really inefficient, involving two table scans. I could do it in a for loop, discarding tuples with keys too small, and break when I hit the first blocking tuple. But for runs like a dog compared to list selection.
Is there a super-efficient, python-esque (2.7) way of doing this?