Python: split a list based on a condition?

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

    Problem with all proposed solutions is that it will scan and apply the filtering function twice. I'd make a simple small function like this:

    def split_into_two_lists(lst, f):
        a = []
        b = []
        for elem in lst:
            if f(elem):
                a.append(elem)
            else:
                b.append(elem)
        return a, b
    

    That way you are not processing anything twice and also are not repeating code.

提交回复
热议问题