Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

I am trying to get all possible pattern from list like:

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

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

That means all possible pattern is 4 (2 case x 2 case), the expect output is:

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 how to, but I can not find any examples (because of I have no idea about "keyword" to search)

I think python has inner libraries/methods to handle it.

like image 403
user3214044 Avatar asked Mar 07 '23 23:03

user3214044


1 Answers

One way to achieve this is via using itertools.product. But for using that, you need to firstly wrap the single elements within your list to another list.

For example, firstly we need to convert your list:

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

to:

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

This can be done via below list comprehension as:

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

Now call itertools.product on the unpacked version of the above 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')]
like image 111
Moinuddin Quadri Avatar answered Apr 28 '23 12:04

Moinuddin Quadri