多个列表的 Itertools 组合,每个列表选择 n 个元素

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)]

如果我没理解错的话,这个问题基本上分为两步:

  1. 从每组中选择n个项目。这可以用 itertools.combinations (或 .permutations 根据你的需要来完成:
a1 = itertools.combinations(a[0], n1)
a2 = itertools.combinations(a[1], n2)
  1. 找到这两个可迭代对象的组合。这几乎就是笛卡尔积的作用:
r = itertools.product(a1, a2)

为了使结果看起来正是您要查找的结果,您可以使用列表理解来连接元组:

r = [list(s1 + s2) for s1, s2 in r