Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python combination generation

I am new to programming and to Python. Not sure how to proceed to achieve this (explained below) problem, hence the question.

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

Example:

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

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

Example here has 3 lists each with 3 items but there can be any n number of lists each containing any m number of elements (so not all lists need to have same number of elements).

All elements of lists are strings and output list also contains strings.

What should I do?

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

like image 885
Phil Avatar asked Oct 29 '12 20:10

Phil


People also ask

What is combination in Python?

This method takes a list and an input r as an input and return an object list of tuples which contain all possible combination of length r in a list form.

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!


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']
like image 128
Ashwini Chaudhary Avatar answered Sep 21 '22 00:09

Ashwini Chaudhary


use a 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]
like image 41
mata Avatar answered Sep 22 '22 00:09

mata