Python: split a list based on a condition?

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

    If you want to make it in FP style:

    good, bad = [ sum(x, []) for x in zip(*(([y], []) if y in goodvals else ([], [y])
                                            for y in mylist)) ]
    

    Not the most readable solution, but at least iterates through mylist only once.

提交回复
热议问题