如何从包含列表和字符串的嵌套列表中找到所有可能的组合? [英] How to find all possible combinations from nested list containing list and strings?
问题描述
我正在尝试从列表中获取所有可能的模式,例如:
I am trying to get all possible pattern from list like:
input_x = ['1', ['2', '2x'], '3', '4', ['5', '5x']]
如我们所见,它在此处有2个嵌套列表['2', '2x']
和['5', '5x']
.
As we see, it has 2 nested list ['2', '2x']
and ['5', '5x']
here.
这意味着所有可能的模式都是4(2格x 2格),预期输出为:
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)
我认为python有内部库/方法来处理它.
I think python has inner libraries/methods to handle it.
推荐答案
实现此目标的一种方法是使用 itertools.product
.但是,要使用此功能,您首先需要将列表中的单个元素包装到另一个列表中.
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']]
收件人:
[['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']]
现在在解压后的版本中调用 itertools.product
以上list
的
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')]
这篇关于如何从包含列表和字符串的嵌套列表中找到所有可能的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!