Python: split a list based on a condition?

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

    itertools.groupby almost does what you want, except it requires the items to be sorted to ensure that you get a single contiguous range, so you need to sort by your key first (otherwise you'll get multiple interleaved groups for each type). eg.

    def is_good(f):
        return f[2].lower() in IMAGE_TYPES
    
    files = [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ('file3.gif', 123L, '.gif')]
    
    for key, group in itertools.groupby(sorted(files, key=is_good), key=is_good):
        print key, list(group)
    

    gives:

    False [('file2.avi', 999L, '.avi')]
    True [('file1.jpg', 33L, '.jpg'), ('file3.gif', 123L, '.gif')]
    

    Similar to the other solutions, the key func can be defined to divide into any number of groups you want.

提交回复
热议问题