Basically what I want to do is take two lists of objects and based on some test and divide them into two lists depending on whether the result is True
or False
. Sort of what filter()
does, except that instead of determining if it's in or out it determines which list/iterator to go to. I've made this attempt using itertools.groupby()
:
import random
from itertools import groupby
class FooObject(object):
def __init__(self):
self.key = random.choice((True, False))
def __repr__(self):
return '<Foo: %s>' % self.key
foos = [FooObject() for _ in range(10)]
left, right = [], []
groups = groupby(sorted(foos, key=lambda o: o.key), lambda o: o.key)
for k, group in groups:
if k:
right = list(group)
else:
left = list(group)
print left
print right
This gets the job done, but just wondering if there is a clearner/simpler way. I realize I could use filter()
(or the equivalent list comprehension) and do it in two passes, but what fun is that?