Combinations of lists

Сахнов Михаил sahnov.m at gmail.com
Wed Oct 3 10:37:17 EDT 2012


>>> t1 = [1,2,3]
>>> t2 = [4,5,6]
>>> [(x,y) for x in t1 for y in t2]
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]


2012/10/3 Steen Lysgaard <boxeakasteen at gmail.com>

> Hi,
>
> I am looking for a clever way to compute all combinations of two lists.
> Look at this example:
>
> h = ['A','A','B','B']
> m = ['a','b']
>
> the resulting combinations should be of the same length as h and each
> element in m can be used twice. The sought after result using h and m from
> above is:
>
> [['aA', 'aA', 'bB', 'bB'],
>  ['aA', 'aB', 'bA', 'bB'],
>  ['aB', 'aB', 'bA', 'bA']]
>
> (the order of the results does not matter i.e. ['aA', 'aA', 'bB', 'bB']
> and ['aA', 'bB', 'aA', 'bB'] are considered the same)
>
> This is achieved by the code below, this however needs to go through all
> possible combinations (faculty of len(h)) and rule out duplicates as they
> occur and this is too much if for example len(h) is 16.
>
> Can anyone guide me to a better solution?
>
> Thanks,
> Steen
>
> h = ['A','A','B','B']
> m = ['a','b']
>
> c = []
> for i in h:
>     c.append([])
>     for j in m:
>         c[-1].append(j+i)
>         c[-1].append(j+i)
>
> combs = []
>
> for a in permutations(range(len(h)),**len(h)):
>     comb = []
>     for i in range(len(h)):
>         comb.append(c[i][a[i]])
>     comb.sort()
>
>     if comb not in combs:
>         combs.append(comb)
>
> print combs
>
> print len(combs)
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>



-- 
--
ICQ:#7499099
JID:soider at jabber.ru
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121003/2331f5a8/attachment.html>


More information about the Python-list mailing list