Combining sets/dictionaries

alex23 wuwei23 at gmail.com
Tue Sep 22 22:55:28 EDT 2009


On Sep 23, 12:44 pm, alex23 <wuwe... at gmail.com> wrote:
> Alfons Nonell-Canals <alfons.non... at upf.edu> wrote:
> > finally I've solved it using a "combinatorics" library which allows to
> > do this kind of things.
>
> If you're using a version of Python > 2.6 you might find that
> itertools.combinations does what you want without requiring the
> additional code.

Actually, that's probably _not_ what you want, sorry. I don't like the
recursive solution you've found, though, especially as you can get the
same result with a generator expression:

>>> set1 = set(['smart', 'dumb']) # the example on the site is easier to follow than your use case, sorry
>>> set2 = set(['hard-working', 'lazy'])
>>> list((a,b) for a in set1 for b in set2)
[('smart', 'lazy'), ('smart', 'hard-working'), ('dumb', 'lazy'),
('dumb', 'hard-working')]

>>> set3 = ['crazy', 'sane', 'boring'] # works with iterators of any size
>>> list((a,b) for a in set1 for b in set3)
[('smart', 'crazy'), ('smart', 'sane'), ('smart', 'boring'), ('dumb',
'crazy'), ('dumb', 'sane'), ('dumb', 'boring')]

Hope this helps.



More information about the Python-list mailing list