Python: split a list based on a condition?

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

    Yet another answer, short but "evil" (for list-comprehension side effects).

    digits = list(range(10))
    odd = [x.pop(i) for i, x in enumerate(digits) if x % 2]
    
    >>> odd
    [1, 3, 5, 7, 9]
    
    >>> digits
    [0, 2, 4, 6, 8]
    

提交回复
热议问题