Python: split a list based on a condition?

前端 未结 30 1840
误落风尘
误落风尘 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:21

    solution

    from itertools import tee
    
    def unpack_args(fn):
        return lambda t: fn(*t)
    
    def separate(fn, lx):
        return map(
            unpack_args(
                lambda i, ly: filter(
                    lambda el: bool(i) == fn(el),
                    ly)),
            enumerate(tee(lx, 2)))
    

    test

    [even, odd] = separate(
        lambda x: bool(x % 2),
        [1, 2, 3, 4, 5])
    print(list(even) == [2, 4])
    print(list(odd) == [1, 3, 5])
    

提交回复
热议问题