Python: split a list based on a condition?

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

    If you don't mind using an external library there two I know that nativly implement this operation:

    >>> files = [ ('file1.jpg', 33, '.jpg'), ('file2.avi', 999, '.avi')]
    >>> IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')
    
    • iteration_utilities.partition:

      >>> from iteration_utilities import partition
      >>> notimages, images = partition(files, lambda x: x[2].lower() in IMAGE_TYPES)
      >>> notimages
      [('file2.avi', 999, '.avi')]
      >>> images
      [('file1.jpg', 33, '.jpg')]
      
    • more_itertools.partition

      >>> from more_itertools import partition
      >>> notimages, images = partition(lambda x: x[2].lower() in IMAGE_TYPES, files)
      >>> list(notimages)  # returns a generator so you need to explicitly convert to list.
      [('file2.avi', 999, '.avi')]
      >>> list(images)
      [('file1.jpg', 33, '.jpg')]
      

提交回复
热议问题