2016-07-06 24 views
-1

我不知道该不该称之为组合排列,所以这个问题就可以讨论您的评论编辑。如何做一个清单的名单组合在Python

我有如下列表:

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

我想这是作为输出:

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

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


环境

  • 蟒蛇3.5.1
+4

你尝试['itertools.product'(https://docs.python.org/3.5/library/itertools.html#itertools.product)? – MisterMiyagi

+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) 
+0

你可以做到这一点,但为什么重新发明轮子?这是一个经典的“itertools.product”问题。 –

相关问题