Combinatorial of elements in Python?
François Ingelrest
athropos at gmail.com
Wed Aug 15 08:39:16 EDT 2007
> > I have 2 (or more) groups of elements, and I want to get all possible
> > unique combinations from all of them. Is there a build-in method to do
> > it?
> >>> ADictionary={"one":["A","B","C","D"],"two":["H","I"]}
> >>> result = set()
> >>> for one in ADictionary["one"]:
> ... for two in ADictionary["two"]:
> ... result.add(one + two)
> ...
> >>> result
> set(['CI', 'CH', 'DH', 'DI', 'AI', 'AH', 'BH', 'BI'])
With a list comprehension:
>>> d={"one":["A","B","C","D"],"two":["H","I"]}
>>> [a+b for a in d['one'] for b in d['two']]
['AH', 'AI', 'BH', 'BI', 'CH', 'CI', 'DH', 'DI']
More information about the Python-list
mailing list