如何在Python中组合列表的列表

时间:2016-07-06 08:37:54

标签: python list python-3.x combinations python-3.5

  

我不知道是否将其称为组合排列,因此可以针对您的评论修改问题。

我有一个列表如下:

[
    ["a"],
    ["b", "c"],
    ["d", "e", "f"]
]

我想将其输出为:

[
    "abd",
    "acd",
    "abe",
    "ace",
    "abf",
    "acf"
]

我的首要任务是使用内置工具或手工制作,而不是使用其他科学模块。但是,如果没有办法,可以使用科学模块。

环境

  • python 3.5.1

1 个答案:

答案 0 :(得分:1)

根据评论的建议,您可以使用itertools.product。或者你可以实现一个简单的递归方法:

def combine(lists, index=0, combination=""):
    if index == len(lists):
        print combination
        return
    for i in lists[index]:
        combine(lists, index+1, combination + i)

lists = [
    ["a"],
    ["b", "c"],
    ["d", "e", "f"]
]

combine(lists)