I have input like:
x = [[1,2,3],[1,2,3,4],[1,2,3,4,5]]
I want to choose one item from each sublist of a list, and - maintaining order - make every possible combination with them, like:
[[1,1,1],[1,1,2],[1,1,3],[1,1,4],[1,1,5],[1,2,1]...]
Each sub-list in the output should include one item from each input sub-list - i.e.: it does not include [5,5,5]
or [4,4,5]
, because the first input sub-list does not include 4
, and only the last includes 5
. Order matters: the output should include [3,4,5]
, but not [5,4,3]
.
How can I get an exhaustive list of results meeting these criteria? I was hoping there would be an itertools
function for this, but I have not been able to find one.
Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!
A. To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.
The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.
I think you want itertools.product
[p for p in itertools.product(*x)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With