all possible matchings of elements of two lists

Mark Dickinson dickinsm at gmail.com
Wed Aug 26 06:52:22 EDT 2009


On Aug 26, 11:05 am, Sandy <dksre... at gmail.com> wrote:
> Hi all,
> I basically want all possible matchings of elements from two lists,
> Ex: [1,2] [a,b,c]
>
> Required:
>    [ [(1,a),(2,b)]
>      [(1,b),(2,c)]
>      [(1,c),(2,b)]
>      [(1,b),(2,a)]
>      [(1,c),(2,a)]
>      [(1,a),(2,c)]
>    ]

If you're using Python 2.6 (or 3.1), you might find the itertools
module helpful:

Python 2.6.2 (r262:71600, Aug 26 2009, 09:40:44)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> for p in itertools.permutations('abc', 2): print zip([1,2], p)
...
[(1, 'a'), (2, 'b')]
[(1, 'a'), (2, 'c')]
[(1, 'b'), (2, 'a')]
[(1, 'b'), (2, 'c')]
[(1, 'c'), (2, 'a')]
[(1, 'c'), (2, 'b')]



--
Mark



More information about the Python-list mailing list