all possible matchings of elements of two lists

S

Sandy

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)]
]

My thought is to get all possible permutations of two lists given and
select any combination and use zip to get the tuples. Repeat this for
all possible combinations.

Any other ideas?
Sandy
 
D

dksr

Ok this is how I do it:
l1 = [1,2]
l2= ['a','b','c']
res = []
l2 = permute(l2)
for i in l2:
lis = [l1,l2]
res.append(zip(*lis))
# or use map depending on what u want
res.append(map(None,*lis))

print res
 
M

Mark Dickinson

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')]
 
J

Jan Kaliszewski

26-08-2009 o 12:05:41 Sandy said:
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)]
]

My thought is to get all possible permutations of two lists given and
select any combination and use zip to get the tuples. Repeat this for
all possible combinations.

Any other ideas?

See: module itertools -- there are (OOTB) some combinatoric generators
that may be useful for you.

*j
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top