Reputation: 213
The problem is to build extended lists out of using two same length lists. for example, there is
qq=['a','b','c']
ww=['d','e','f']
my_function(qq,ww)
#I want to see output like:
output = [['a','b','c'],['a','b','f'],['a','e','c'],['a','e','f'],['d','e','f'],['d','e','c'],['d','b','f'],['d','b','c']]
all the combinations of making the same length list with a constraint of:
The important thing is the elements' position in the list.
so the function takes two same length list of strings. and returns the list of the combinations. How should I write this?
Upvotes: 0
Views: 105
Reputation: 54148
You want, from your 2 lists, to do the product of the pairs [a,d] * [b,e] * [c,f]
. Using zip
to pair, and product
to combine them all makes the whole to
zip
product
from itertools import product
def custom_product(valuesA, valuesB):
return list(product(*zip(valuesA, valuesB))) # return list of tuple
def custom_product(valuesA, valuesB):
return list(map(list, product(*zip(valuesA, valuesB)))) # return list of list
CODE DEMO
Upvotes: 8
Reputation: 654
Here's a recursive solution.
The base case is of course when each list has just one item and we take each list as possible output. For longer lists, you find all the possible arrangements of the lists not counting the first items, and then return those items with each of the first items.
def solve(list1, list2):
if len(list1) != len(list2):
throw ValueError("Lists should be same length")
if len(list1) == 0:
return []
if len(list1) == 1:
return [[list1[0], list2[0]]
children = solve(list1[1:], list2[1:])
return [[list1[0]] + child for child in children] + [[list2[0]] + child for child in children]]
Upvotes: 1