Stopping List Selection?
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 firs
Solution 1:
You can simply filter the tuples from the list as a generator expression and then you can stop taking the values from the generator expression when you get the first tuple whose second element is -1
, like this
>>>s = [(0,-1), (1,0), (2,-1), (3,0), (4,0), (5,-1), (6,0), (7,-1)]>>>from itertools import takewhile>>>X = 3>>>list(takewhile(lambda x: x[1] != -1, (item for item in s if item[0] >= X)))
[(3, 0), (4, 0)]
Here, the generator expression, (item for item in s if item[0] >= X)
will give values one-by-one, on demand, (they are not generated all at once, so we save memory here) which are greater than or equal to X
.
Then, we take values from that generator expression, only till we find a tuple whose second element is not equal to -1
, with itertools.takewhile
.
Solution 2:
Here's a slightly hacky to implement takewhile
as part of a generator expression:
def stop(): raise StopIteration
result = (
stop() if item[1] == -1else
item
for item in s
if item[0] >= X
)
Or with different phrasing:
defuntil(cond):
if cond: raise StopIteration
returnTrue
result = (
item for item in s
if item[0] >= X
and until(item[1] == -1)
)
Post a Comment for "Stopping List Selection?"