Quantcast
Channel: How can I partition (split up, divide) a list based on a condition? - Stack Overflow
Viewing all articles
Browse latest Browse all 41

Answer by MSeifert for How can I partition (split up, divide) a list based on a condition?

$
0
0

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')]

Viewing all articles
Browse latest Browse all 41

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>