Python: split a list based on a condition?

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

    First go (pre-OP-edit): Use sets:

    mylist = [1,2,3,4,5,6,7]
    goodvals = [1,3,7,8,9]
    
    myset = set(mylist)
    goodset = set(goodvals)
    
    print list(myset.intersection(goodset))  # [1, 3, 7]
    print list(myset.difference(goodset))    # [2, 4, 5, 6]
    

    That's good for both readability (IMHO) and performance.

    Second go (post-OP-edit):

    Create your list of good extensions as a set:

    IMAGE_TYPES = set(['.jpg','.jpeg','.gif','.bmp','.png'])
    

    and that will increase performance. Otherwise, what you have looks fine to me.

提交回复
热议问题