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.
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.
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!
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']
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]
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