Skip to content
Advertisement

Separate combination of two separate lists keeping the correspondence/dependence on each other

I have two lists of same length which have one to one correspondence:

a = [1,2,3,4]
b = [6,7,8,9]

I want to find combinations of these two lists separately. But the indices of combined elements must be the same for both lists.

For example, if I do:

list(itertools.combinations(a,2))

I may get

[(1,2),(1,3),(1,4),(3,2),(4,2),(4,3)]  

I could’ve got

[(2,1),(3,1),(4,1),(2,3),(2,4),(3,4)]

too because both are the same.

So whatever the combination I get I want the same indices combined for the second list too.

So if

list(itertools.combinations(a,2))

gives me

[(1,2),(1,3),(1,4),(3,2),(4,2),(4,3)]

then

list(itertools.combinations(b,2))

should give me

[(6,7),(6,8),(6,9),(8,7),(9,7),(9,8)]

or if

list(itertools.combinations(a,2))

gives me

[(2,1),(3,1),(4,1),(2,3),(2,4),(3,4)]

then

list(itertools.combinations(b,2))

should give me

[(7,6),(8,6),(9,6),(7,8),(7,9),(8,9)]

Advertisement

Answer

You could generate combinations on the indices and then index a and b. For instance:

a = [1,2,3,4]
b = [6,7,8,9]
for i0,i1 in itertools.combinations(range(len(a)), 2):
  print("{0},{1}  -->  {2},{3}".format(a[i0],a[i1],b[i0],b[i1]))


1,2  -->  6,7
1,3  -->  6,8
1,4  -->  6,9
2,3  -->  7,8
2,4  -->  7,9
3,4  -->  8,9
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement