具有长度的列表列表的组合

时间:2014-05-01 14:15:01

标签: python list combinations itertools

我有一份清单清单 a= [ [1,2,3],[4,5,6,7],[8,9,10] ]

我希望在列表中获得长度为2的所有可能组合 即

[ [1,4] ,[1,5], [1,6] , [1,7] , [1,8], [1,9] , [1,10] , [2,4], [2,5] etc etc ]

1 个答案:

答案 0 :(得分:3)

您可以使用itertools.combinationsitertools.product

>>> from itertools import combinations, product, chain, starmap
>>> [p for c in combinations(a, 2) for p in product(*c)]
[(1, 4), (1, 5), (1, 6), (1, 7), (2, 4), (2, 5), (2, 6), (2, 7), (3, 4), (3, 5), (3, 6), (3, 7), (1, 8), (1, 9), (1, 10), (2, 8), (2, 9), (2, 10), (3, 8), (3, 9), (3, 10), (4, 8), (4, 9), (4, 10), (5, 8), (5, 9), (5, 10), (6, 8), (6, 9), (6, 10), (7, 8), (7, 9), (7, 10)]
#or list(chain(*starmap(product, combinations(a, 2))))