如何在Python中获得1到n个列表的所有组合

时间:2016-02-17 17:59:17

标签: python list combinations

我有一个列表列表例如:[[a,b,c],[1,2,3],[x,y]]

我想要制作[a],[b],...,[a,1],[a,2],...,[a,1,x],[a,1,y]

通过解决方案,我已经看到itertools.combinations如何生成单个列表的所有组合,而itertools.product可以产生最高级别的组合,即上例中的3个元素

我不确定如何在不破坏列表结构列表的情况下浏览1到n列表的所有组合,并使用itertools.combinations进行一些布尔检查以确保我没有组合来自同一个清单。

3 个答案:

答案 0 :(得分:2)

我认为这是你正在寻找的东西:

>>> import itertools
>>> x = [['a', 'b', 'c'], [1, 2, 3], ['x', 'y']] # your list of lists
>>> [tup for sublist in [itertools.product(*x[:n+1]) for n in range(len(x))] 
         for tup in sublist]
[('a',), ('b',), ('c',), 
 ('a', 1), ('a', 2), ('a', 3), 
 ('b', 1), ('b', 2), ('b', 3), 
 ('c', 1), ('c', 2), ('c', 3), 
 ('a', 1, 'x'), ('a', 1, 'y'), ('a', 2, 'x'), ('a', 2, 'y'), ('a', 3, 'x'), ('a', 3, 'y'), 
 ('b', 1, 'x'), ('b', 1, 'y'), ('b', 2, 'x'), ('b', 2, 'y'), ('b', 3, 'x'), ('b', 3, 'y'), 
 ('c', 1, 'x'), ('c', 1, 'y'), ('c', 2, 'x'), ('c', 2, 'y'), ('c', 3, 'x'), ('c', 3, 'y')]

您只需要对列表清单中的所有前缀(itertools.productx[:1],...)进行x[:2]。外部列表理解仅用于展平内部列表理解生成的列表列表。

答案 1 :(得分:2)

之前的帖子提供了涉及嵌套理解的简明解决方案,但遗漏了可能的一组子列表中的几个产品,如routes.Add("Admin_Subdomain", new SubdomainRouteP( "Tenant", "admin/{action}/{id}", new { controller = "Admin", action = "Index", id = UrlParameter.Optional })); routes.Add("Public_Subdomain", new SubdomainRouteP( "Tenant", "public/{action}/{id}", new { controller = "Public", action = "Index", id = UrlParameter.Optional })); // This is the MVC default Route routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }); 。我将尝试以更易读的方式将其分解:

('a', 'x')

答案 2 :(得分:1)

您可以在列表推导中使用itertools.combinationsitertools.product()来计算所有单个,对和三元组的乘积:

>>> from itertools import product
>>> lst = [['a','b','c'],[1,2,3],['x','y']]
>>> [[list(product(*t)) for t in combinations(lst,i)] for i in range(1,len(lst)+1)]
[[[('a',), ('b',), ('c',)], [(1,), (2,), (3,)], [('x',), ('y',)]], 
 [[('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)], [('a', 'x'), ('a', 'y'), ('b', 'x'), ('b', 'y'), ('c', 'x'), ('c', 'y')], [(1, 'x'), (1, 'y'), (2, 'x'), (2, 'y'), (3, 'x'), (3, 'y')]],
[[('a', 1, 'x'), ('a', 1, 'y'), ('a', 2, 'x'), ('a', 2, 'y'), ('a', 3, 'x'), ('a', 3, 'y'), ('b', 1, 'x'), ('b', 1, 'y'), ('b', 2, 'x'), ('b', 2, 'y'), ('b', 3, 'x'), ('b', 3, 'y'), ('c', 1, 'x'), ('c', 1, 'y'), ('c', 2, 'x'), ('c', 2, 'y'), ('c', 3, 'x'), ('c', 3, 'y')]]]