Thomas Johnson
Thomas Johnson

Reputation: 11698

How can I get a set of (possibly overlapping) slices in a Python list based on elements that match a criteria?

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 f(e) is e%2==0, and x=3 I'd like to get [[2,3,4],[4,5]].

Is there an elegant or "pythonic" way to do this?

Upvotes: 0

Views: 206

Answers (2)

BioGeek
BioGeek

Reputation: 22887

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

Upvotes: 1

poke
poke

Reputation: 388023

>>> f = lambda e: e % 2 == 0
>>> x = 3
>>> l = [1, 2, 3, 4, 5]
>>> def makeSublists(lst, length, f):
        for i in range(len(lst)):
            if f(lst[i]):
                yield lst[i:i+length]
>>> list(makeSublists(l, x, f))
[[2, 3, 4], [4, 5]]
>>> list(makeSublists(list(range(10)), 5, f))
[[0, 1, 2, 3, 4], [2, 3, 4, 5, 6], [4, 5, 6, 7, 8], [6, 7, 8, 9], [8, 9]]

Upvotes: 3

Related Questions