Quantcast
Viewing all articles
Browse latest Browse all 41

Answer by David for How can I partition (split up, divide) a list based on a condition?

If the list is made of groups and intermittent separators, you can use:

def split(items, p):    groups = [[]]    for i in items:        if p(i):            groups.append([])        groups[-1].append(i)    return groups

Usage:

split(range(1,11), lambda x: x % 3 == 0)# gives [[1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]

Viewing all articles
Browse latest Browse all 41

Trending Articles