[英]Itertools combinations of multiple list selecting n elements per list
我需要组合一个列表列表,例如选择每个列表的 n 个元素
a=[[1,2,3,4,5],[6,7,8,9,10]]
n1=2
n2=3
所以我的结果可能是这样的:
r=[[1,2,6,7,8],[1,2,6,7,9],...,[4,5,7,8,9],[4,5,8,9,10]]
有什么干净的方法可以做到吗? 或者我应该将我的列表分成更小的尺寸并使用 for 循环来调用 itertools?
简单的分别生成两个列表的组合,然后取两个生成器的笛卡尔积:
from itertools import product, combinations
r_gen = product(combinations(a[0], n1), combinations(a[1], n2))
r = (a + b for a, b in r_gen)
r
产生的前 10 个元素是
[(1, 2, 6, 7, 8),
(1, 2, 6, 7, 9),
(1, 2, 6, 7, 10),
(1, 2, 6, 8, 9),
(1, 2, 6, 8, 10),
(1, 2, 6, 9, 10),
(1, 2, 7, 8, 9),
(1, 2, 7, 8, 10),
(1, 2, 7, 9, 10),
(1, 2, 8, 9, 10)]
如果我理解正确的话,这个问题基本上有两个步骤:
itertools.combinations
(或.permutations
根据您的需要:a1 = itertools.combinations(a[0], n1)
a2 = itertools.combinations(a[1], n2)
r = itertools.product(a1, a2)
为了使结果看起来正是您要查找的内容,您可以使用列表理解来连接元组:
r = [list(s1 + s2) for s1, s2 in r
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.