Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Choose One Item from Every List but Make Every Possible Combination

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.

like image 672
5813 Avatar asked Oct 17 '13 03:10

5813


People also ask

How do you generate all possible combinations of one list?

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!

How do you get all possible combinations without repetition in Python?

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.

How do you generate all possible combinations of two lists in Python?

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.


1 Answers

I think you want itertools.product

[p for p in itertools.product(*x)]
like image 174
tacaswell Avatar answered Oct 09 '22 04:10

tacaswell