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 Brian for How can I partition (split up, divide) a list based on a condition?

$
0
0

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_TYPESfiles = [ ('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.


Viewing all articles
Browse latest Browse all 41

Trending Articles



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