Python: split a list based on a condition?

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

    For perfomance, try itertools.

    The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.

    See itertools.ifilter or imap.

    itertools.ifilter(predicate, iterable)

    Make an iterator that filters elements from iterable returning only those for which the predicate is True

提交回复
热议问题