Python: split a list based on a condition?

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

    For example, splitting list by even and odd

    arr = range(20)
    even, odd = reduce(lambda res, next: res[next % 2].append(next) or res, arr, ([], []))
    

    Or in general:

    def split(predicate, iterable):
        return reduce(lambda res, e: res[predicate(e)].append(e) or res, iterable, ([], []))
    

    Advantages:

    • Shortest posible way
    • Predicate applies only once for each element

    Disadvantages

    • Requires knowledge of functional programing paradigm

提交回复
热议问题