具有长度的列表列表的组合(combinations of list of lists with length)
我有一个列表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 ]
I have a list of lists a= [ [1,2,3],[4,5,6,7],[8,9,10] ]
I want to get all possible combinations of length 2 among the lists ie
[ [1,4] ,[1,5], [1,6] , [1,7] , [1,8], [1,9] , [1,10] , [2,4], [2,5] etc etc ]
最满意答案
您可以使用itertools.combinations和itertools.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))))You can use itertools.combinations and itertools.product for this:
>>> 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))))更多推荐
发布评论