假设我有一个有序的组合列表,并替换为 n=4(对象)和 r=3(样本):
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 1, 4]
[1, 2, 2]
[1, 2, 3]
[1, 2, 4]
[1, 3, 3]
[1, 3, 4]
[1, 4, 4]
[2, 2, 2]
[2, 2, 3]
[2, 2, 4]
[2, 3, 3]
[2, 3, 4]
[2, 4, 4]
[3, 3, 3]
[3, 3, 4]
[3, 4, 4]
[4, 4, 4]
如何获取包含给定对象的所有行的索引并生成所有相应的行(生成的行中元素的顺序并不重要,但行必须与索引的顺序相同)。
例如
给定元素 2 和上面的数组,我希望函数返回
[[1, 1, 2],
[1, 2, 2],
[1, 2, 3]
[1, 2, 4]
[2, 2, 2]
[2, 2, 3]
[2, 2, 4]
[2, 3, 3]
[2, 3, 4]
[2, 4, 4]]
当然,我可以每次创建这个列表并选择所需的元素等,但我想知道是否有一个公式可以做到这一点 - 在非常大的数组的情况下节省内存等。
如果我自己解决了,我会发布解决方案。
itertools.combinations_with_replacements
生成带有替换的组合
要强制将某个元素包含在组合中:使用少一个元素进行替换来生成组合,然后添加所需的元素。
from itertools import combinations_with_replacement
print(list( combinations_with_replacement((1,2,3,4), 3) ))
# [(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 1, 4), (1, 2, 2), (1, 2, 3), (1, 2, 4), (1, 3, 3), (1, 3, 4), (1, 4, 4), (2, 2, 2), (2, 2, 3), (2, 2, 4), (2, 3, 3), (2, 3, 4), (2, 4, 4), (3, 3, 3), (3, 3, 4), (3, 4, 4), (4, 4, 4)]
def combinations_with_replacement_with_forced_element(seq, elem, r):
return (sorted((elem, *c)) for c in combinations_with_replacement(seq, r-1))
print(list( combinations_with_replacement_with_forced_element((1,2,3,4), elem=2, r=3) ))
# [[1, 1, 2], [1, 2, 2], [1, 2, 3], [1, 2, 4], [2, 2, 2], [2, 2, 3], [2, 2, 4], [2, 3, 3], [2, 3, 4], [2, 4, 4]]