Combinatorial of elements in Python?

Mikael Olofsson mikael at isy.liu.se
Wed Aug 15 08:45:57 EDT 2007


Sebastian Bassi wrote:
> 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"]}
>
> I want to have all possible combinations from "one" and "two", that is:
> [snip]

Not at all complicated. My solution:

 >>> A={'one':['A','B','C','D'],'two':['H','I']}
 >>> [x+y for x in A['one'] for y in A['two']]
['AH', 'AI', 'BH', 'BI', 'CH', 'CI', 'DH', 'DI']

HTH
/MiO

-- 
/Mikael Olofsson
Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

-----------------------------------------------------------------------
E-Mail:  mikael at isy.liu.se
WWW:     http://www.dtr.isy.liu.se/en/staff/mikael
Phone:   +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
-----------------------------------------------------------------------
Linköpings kammarkör: www.kammarkoren.com   Vi söker tenorer och basar! 




More information about the Python-list mailing list