Python combination generation

I am new to programming and Python. You do not know how to do this (explained below), so the question is.

I have n number of lists, each of which contains 1 or more elements. I want to have a new list with all possible combinations that uses one element from each list once and always.

Example:

list_1 = ['1','2','3'] list_2 = ['2','5','7'] list_3 = ['9','9','8'] 

Result: ['129', '129', '128', '159', '159', '158', '179', '179', '178', '229', '229', '228', '259', '259', '258', '329', '329', '328', '359', '359','358', '379', '379', '378']

An example has 3 lists, each of which contains 3 elements, but there can be any number of lists, each of which contains any number of elements (therefore, not all lists must have the same number of elements).

All list items are strings, and the output list also contains strings.

What should I do?

I looked at itertools.combinations, but I have no idea how to use it for this task.

+6
source share
2 answers

use itertools.product() here:

 >>> list_1 = ['1','2','3'] >>> list_2 = ['2','5','7'] >>> list_3 = ['9','9','8'] >>> from itertools import product >>> ["".join(x) for x in product(list_1,list_2,list_3)] ['129', '129', '128', '159', '159', '158', '179', '179', '178', '229', '229', '228', '259', '259', '258', '279', '279', '278', '329', '329', '328', '359', '359', '358', '379', '379', '378'] 
+11
source

use list comprehension:

 result = ["%s%s%s" % (i,j,k) for i in list_1 for j in list_2 for k in list_3] 

or use itertools :

 product = itertools.product(list_1, list_2, list_3) result = [''.join(p) for p in product] 
+6
source

All Articles