具有长度的列表列表的组合(combinations of list of lists with length)

系统教程 行业动态 更新时间:2024-06-14 17:04:03
具有长度的列表列表的组合(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))))

更多推荐

本文发布于:2023-04-24 21:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/b8e4af306929e7fbc503e898cce3415d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   列表   长度   combinations   lists

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!