如何从包含列表和字符串的嵌套列表中查找所有可能的组合?

use*_*044 4 python list

我试图从列表中获取所有可能的模式,如:

input_x = ['1', ['2', '2x'], '3', '4', ['5', '5x']]
Run Code Online (Sandbox Code Playgroud)

正如我们所见,它有2个嵌套列表['2', '2x']['5', '5x']这里.

这意味着所有可能的模式都是4(2个案例x 2个案例),期望输出为:

output1 = ['1','2' , '3', '4',  '5']
output2 = ['1','2x', '3', '4',  '5']
output3 = ['1','2' , '3', '4', '5x']
output4 = ['1','2x', '3', '4', '5x']
Run Code Online (Sandbox Code Playgroud)

我试图搜索如何,但我找不到任何例子(因为我不知道搜索"关键字")

我认为python有内部库/方法来处理它.

Moi*_*dri 6

实现这一目标的一种方法是通过使用itertools.product.但是为了使用它,您需要首先将列表中的单个元素包装到另一个列表中.

例如,首先我们需要转换您的列表:

['1', ['2', '2x'], '3', '4', ['5', '5x']]
Run Code Online (Sandbox Code Playgroud)

至:

[['1'], ['2', '2x'], ['3'], ['4'], ['5', '5x']]
Run Code Online (Sandbox Code Playgroud)

这可以通过以下列表理解来完成:

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']]
Run Code Online (Sandbox Code Playgroud)

现在调用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')]
Run Code Online (Sandbox Code Playgroud)