Python: split a list based on a condition?

前端 未结 30 1842
误落风尘
误落风尘 2020-11-22 06:56

What\'s the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:

30条回答
  •  情深已故
    2020-11-22 07:11

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

提交回复
热议问题