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

$
0
0

Already quite a few solutions here, but yet another way of doing that would be -

anims = []images = [f for f in files if (lambda t: True if f[2].lower() in IMAGE_TYPES else anims.append(t) and False)(f)]

Iterates over the list only once, and looks a bit more pythonic and hence readable to me.

>>> files = [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi'), ('file1.bmp', 33L, '.bmp')]>>> IMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')>>> anims = []>>> images = [f for f in files if (lambda t: True if f[2].lower() in IMAGE_TYPES else anims.append(t) and False)(f)]>>> print '\n'.join([str(anims), str(images)])[('file2.avi', 999L, '.avi')][('file1.jpg', 33L, '.jpg'), ('file1.bmp', 33L, '.bmp')]>>>

Viewing all articles
Browse latest Browse all 41

Trending Articles



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