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

标签 python list

我正在尝试从列表中获取所有可能的模式,例如:

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

正如我们所见,这里有 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']

我试图搜索如何,但我找不到任何示例(因为我不知道要搜索的“关键字”)

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

最佳答案

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

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

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

关于python - 如何从包含列表和字符串的嵌套列表中找到所有可能的组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48635310/

相关文章:

python - 即使在 pygame 中释放 key 后,我的 Sprite 仍然继续移动

python - TypeError :'datetime.datetime' 对象不可订阅

python - 将多个方法应用于单个对象?

delphi - 从列表中删除重复项

Python 2.7 - IPython 'raw_input' 并附加到列表 - 在每个项目之前添加 'u'

python - 有效地从文件中读取主版本号

从 stdin 读取时,python 交互模式不起作用

python - 检查目录是否包含具有给定扩展名的文件

list - 如何测试两个无序列表的相等性?

html - ionic 列表项单击在另一个 HTML 页面中显示详细信息