I have two lists of same length which have one to one correspondence:
JavaScript
x
3
1
a = [1,2,3,4]
2
b = [6,7,8,9]
3
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:
JavaScript
1
2
1
list(itertools.combinations(a,2))
2
I may get
JavaScript
1
2
1
[(1,2),(1,3),(1,4),(3,2),(4,2),(4,3)]
2
I could’ve got
JavaScript
1
2
1
[(2,1),(3,1),(4,1),(2,3),(2,4),(3,4)]
2
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
JavaScript
1
2
1
list(itertools.combinations(a,2))
2
gives me
JavaScript
1
2
1
[(1,2),(1,3),(1,4),(3,2),(4,2),(4,3)]
2
then
JavaScript
1
2
1
list(itertools.combinations(b,2))
2
should give me
JavaScript
1
2
1
[(6,7),(6,8),(6,9),(8,7),(9,7),(9,8)]
2
or if
JavaScript
1
2
1
list(itertools.combinations(a,2))
2
gives me
JavaScript
1
2
1
[(2,1),(3,1),(4,1),(2,3),(2,4),(3,4)]
2
then
JavaScript
1
2
1
list(itertools.combinations(b,2))
2
should give me
JavaScript
1
2
1
[(7,6),(8,6),(9,6),(7,8),(7,9),(8,9)]
2
Advertisement
Answer
You could generate combinations on the indices and then index a and b. For instance:
JavaScript
1
13
13
1
a = [1,2,3,4]
2
b = [6,7,8,9]
3
for i0,i1 in itertools.combinations(range(len(a)), 2):
4
print("{0},{1} --> {2},{3}".format(a[i0],a[i1],b[i0],b[i1]))
5
6
7
1,2 --> 6,7
8
1,3 --> 6,8
9
1,4 --> 6,9
10
2,3 --> 7,8
11
2,4 --> 7,9
12
3,4 --> 8,9
13