Python: split a list based on a condition?

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

    I think a generalization of splitting a an iterable based on N conditions is handy

    from collections import OrderedDict
    def partition(iterable,*conditions):
        '''Returns a list with the elements that satisfy each of condition.
           Conditions are assumed to be exclusive'''
        d= OrderedDict((i,list())for i in range(len(conditions)))        
        for e in iterable:
            for i,condition in enumerate(conditions):
                if condition(e):
                    d[i].append(e)
                    break                    
        return d.values()
    

    For instance:

    ints,floats,other = partition([2, 3.14, 1, 1.69, [], None],
                                  lambda x: isinstance(x, int), 
                                  lambda x: isinstance(x, float),
                                  lambda x: True)
    
    print " ints: {}\n floats:{}\n other:{}".format(ints,floats,other)
    
     ints: [2, 1]
     floats:[3.14, 1.69]
     other:[[], None]
    

    If the element may satisfy multiple conditions, remove the break.

提交回复
热议问题