mimoralea
mimoralea

Reputation: 9986

How to get all possible combinations of two different lists?

I'm having so much trouble understanding my issue:

I got 2 lists:

from = ['A', 'B', 'C']
to = ['D', 'E', 'F']

I need to produce a matrix that combines each item from one list to the other as such:

final = [[['A', 'D'], ['B', 'E'], ['C', 'F']],
         [['A', 'D'], ['B', 'F'], ['C', 'E']],
         [['A', 'E'], ['B', 'F'], ['C', 'D']],
         [['A', 'E'], ['B', 'D'], ['C', 'F']],
         [['A', 'F'], ['B', 'D'], ['C', 'E']],
         [['A', 'F'], ['B', 'E'], ['C', 'D']]]

I was trying to do this with this:

for i in range(len(initial)):
    for j in range(len(transformed)):
        self.semantic_networks[j][i][0] = self.initial_figure[i]['name']
        self.semantic_networks[i][j][1] = self.transformed_figure[(j + i) % len(self.transformed_figure)]['name']

But, I'm getting only the top:

[['A', 'D'], ['B', 'E'], ['C', 'F']]
[['A', 'E'], ['B', 'F'], ['C', 'D']]
[['A', 'F'], ['B', 'D'], ['C', 'E']]
[[0, 0], [0, 0], [0, 0]]
[[0, 0], [0, 0], [0, 0]]
[[0, 0], [0, 0], [0, 0]]

What am I trying to get? Combination? Permutation? Combination of combinations??

Any hints???

Upvotes: 1

Views: 171

Answers (2)

Simeon Visser
Simeon Visser

Reputation: 122496

It seems you want the combination of all possible permutations:

import itertools
a = ['A', 'B', 'C']
b = ['D', 'E', 'F']
items = zip(itertools.permutations(a), itertools.permutations(b))

Upvotes: -1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251116

Apply itertools.permutations on the second list and then zip each permutation with first list.

from itertools import permutations

lst1 = ['A', 'B', 'C']
lst2 = ['D', 'E', 'F']

for p in permutations(lst2):
    print zip(lst1, p)
#
[('A', 'D'), ('B', 'E'), ('C', 'F')]
[('A', 'D'), ('B', 'F'), ('C', 'E')]
[('A', 'E'), ('B', 'D'), ('C', 'F')]
[('A', 'E'), ('B', 'F'), ('C', 'D')]
[('A', 'F'), ('B', 'D'), ('C', 'E')]
[('A', 'F'), ('B', 'E'), ('C', 'D')]

Upvotes: 4

Related Questions