【问题标题】:How to Make A Combination of Lists of A List in Python [duplicate]如何在Python中制作列表的列表组合[重复]
【发布时间】:2016-11-08 05:53:24
【问题描述】:

我不知道是叫它combination还是permutation,所以可以根据您的评论编辑问题。

我有一个如下列表:

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

我希望它输出为:

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

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


环境

  • python 3.5.1

【问题讨论】:

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


【解决方案1】:

根据 cmets 的建议,您可以使用 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)

【讨论】:

  • 你可以这样做,但为什么要重新发明轮子呢?这是一个经典的itertools.product 问题。
猜你喜欢
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 1970-01-01
  • 2013-12-20
  • 2015-07-29
  • 2018-04-02
相关资源
最近更新 更多