How to find all possible combinations from a nested list containing a list and strings?

I am trying to get all possible templates from a list, for example:

input_x = ['1', ['2', '2x'], '3', '4', ['5', '5x']]

As we can see, it has 2 sub-list ['2', '2x']and ['5', '5x']here.

This means that the whole possible pattern is 4 (case 2 of case x 2), wait output:

output1 = ['1','2' , '3', '4',  '5']
output2 = ['1','2x', '3', '4',  '5']
output3 = ['1','2' , '3', '4', '5x']
output4 = ['1','2x', '3', '4', '5x']

I tried to search, but I can not find any examples (due to the fact that I have no idea about the "keyword" for the search)

I think python has internal libraries / methods for handling it.

+4
source share
2 answers

One way to achieve this is to use itertools.product. But for this you need to first transfer individual items to your list in another list.

, -, :

['1', ['2', '2x'], '3', '4', ['5', '5x']]

[['1'], ['2', '2x'], ['3'], ['4'], ['5', '5x']]

:

formatted_list = [(l if isinstance(l, list) else [l]) for l in my_list]
# Here `formatted_list` is containing the elements in your desired format, i.e.:
#    [['1'], ['2', '2x'], ['3'], ['4'], ['5', '5x']]

itertools.product list:

>>> from itertools import product

#                v  `*` is used to unpack the `formatted_list` list
>>> list(product(*formatted_list))
[('1', '2', '3', '4', '5'), ('1', '2', '3', '4', '5x'), ('1', '2x', '3', '4', '5'), ('1', '2x', '3', '4', '5x')]
+6

-, - :

input_x = ['1', ['2', '2x'], '3', '4', ['5', '5x'],['6','6x']]

import itertools
non_li=[]
li=[]
for i in input_x:
    if isinstance(i,list):
        li.append(i)
    else:
        non_li.append(i)



for i in itertools.product(*li):
    sub=non_li[:]
    sub.extend(i)
    print(sorted(sub))

:

['1', '2', '3', '4', '5', '6']
['1', '2', '3', '4', '5', '6x']
['1', '2', '3', '4', '5x', '6']
['1', '2', '3', '4', '5x', '6x']
['1', '2x', '3', '4', '5', '6']
['1', '2x', '3', '4', '5', '6x']
['1', '2x', '3', '4', '5x', '6']
['1', '2x', '3', '4', '5x', '6x']
0

Source: https://habr.com/ru/post/1693226/


All Articles