Suppose I have a python list
l=[1,2,3,4,5]. I would like to find all x-element lists starting with elements that satisfy a function
f(e), or the sublist going to the end of
l if there aren't enough items. For instance, suppose
x=3 I'd like to get
Is there an elegant or "pythonic" way to do this?
Using a list comprehension:
>>> l = range(1,6) >>> x = 3 >>> def f(e): return e%2 == 0 >>> [l[i:i+x] for i, j in enumerate(l) if f(j)] [[2, 3, 4], [4, 5]]