Reputation: 429
I am looking for a method to generate all possible combinations of a list of lists, under the condition that there should only be "elementwise" combinations. Thus, if we have the lists [1,2] and [3,4], then the outcome [3,2] is allowed, but [4,2] is not allowed. With itertools.product(*lists) the last outcome is included.
Thus, I want the following output: [1,2], [3,2], [1,4], [3,4], and the following options should be 'skipped': [4,2], [1,3]. Note that the order is important! Thus I do not allow [2,3], just [3,2].
I know that I can check for this afterwards, but since I am generating many many lists in my code, I rather avoid this.
Upvotes: 1
Views: 435
Reputation:
You could store the two lists in one list of lists and then after transposing the container list, use itertools.product()
on it.
import itertools
original_list = [[1,2], [3,4]]
transposed_list = list(map(list, zip(*original_list)))
print(list(itertools.product(*transposed_list)))
Outputs:
[(1, 2), (1, 4), (3, 2), (3, 4)]
EDIT | Explaining how the list was transposed:
By definition, transposing is the process of exchanging places.
*original_list
means [1,2]
and [3,4]
. The asterisk refers to the elements of the list, rather than the list as a whole
zip
basically pairs values together 'element-wise':
e.g. with our original_list
we have [1,2]
and [3,4]
. Calling zip on our elements will result in (1,3)
and (2,4)
. The values were paired element-wise.
Note that the resulting pairs are not in list form.
map
applies a function to every element in an input list. In our example,
we want to apply the (built-in) list
function to our element-wise pairs - i.e. convert each tuple of pairs into a list. This is what turns (1,3)
and (2,4)
into [1,3]
and [2,4]
Finally, convert our result from the mapping into a containing list, holding our element-wise pairs, producing [ [1,3], [2,4] ]
Upvotes: 3