Python: split a list based on a condition?

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

    Personally, I like the version you cited, assuming you already have a list of goodvals hanging around. If not, something like:

    good = filter(lambda x: is_good(x), mylist)
    bad = filter(lambda x: not is_good(x), mylist)
    

    Of course, that's really very similar to using a list comprehension like you originally did, but with a function instead of a lookup:

    good = [x for x in mylist if is_good(x)]
    bad  = [x for x in mylist if not is_good(x)]
    

    In general, I find the aesthetics of list comprehensions to be very pleasing. Of course, if you don't actually need to preserve ordering and don't need duplicates, using the intersection and difference methods on sets would work well too.

提交回复
热议问题