Meet Nandu
Meet Nandu

Reputation: 13

Find different combinations from two lists

Given two lists of any length, I want to find all possible combinations between the two lists and then add a dictionary pair of the combination in the new list.

For example, the two lists are:

List1 - ['A', 'B']

List2 - [1, 2]

The resultant list should have the values:

[{'A':1, 'B':1}, {'A':1,'B':2}, {'A':2, 'B':1}, {'A':2, 'B':2}]

All the solutions I found were just giving the possible combinations. So, suppose I have a list of length 3 and 2. The possible combinations would have only 6 values. But, according to my requirement, there would be 8 values.

The code I used:

first_list = ['A', 'B', 'C'] 
second_list = [1, 2]
 
combinations = [(a,b) for a in first_list for b in second_list]

For which the output comes as:

[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

While the output I want is:

[{'A':1, 'B':1, 'C':1},
 {'A':1, 'B':1, 'C':2},
 {'A':1, 'B':2, 'C':1},
 {'A':1, 'B':2, 'C':2},
 {'A':2, 'B':1, 'C':1},
 {'A':2, 'B':1, 'C':2},
 {'A':2, 'B':2, 'C':1},
 {'A':2, 'B':2, 'C':2}]

Upvotes: 1

Views: 183

Answers (2)

quamrana
quamrana

Reputation: 39354

You can use itertools.product to create part of the combinations:

from itertools import product

first_list = ['A', 'B', 'C'] 
second_list = [1, 2]

out = product(second_list, repeat=len(first_list))

combinations = [{f:s for (f,s) in zip(first_list, c)} for c in out]

print(combinations)

Output as required.

Upvotes: 2

batuhand
batuhand

Reputation: 475

You should look up here

You can use

list1 = ["a", "b", "c"]
list2 = [1, 2]
all_combinations = []

list1_permutations = itertools.permutations(list1, len(list2))
Get all permutations of `list1` with length 2

for each_permutation in list1_permutations:
    zipped = zip(each_permutation, list2)
    all_combinations.append(list(zipped))

print(all_combinations)

Output

[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]

Upvotes: 0

Related Questions