使用带有替换的组合后,如何删除带有我不想要的组合的元组

After using combinations with replacement, how to remove tuples with combinations that I don't want

我正在尝试获取遵循如下模式的列表(或元组)列表:

[1,1,1,2]
[1,1,2,2]
[1,2,2,2]
[1,2,2,3]
[1,2,3,3]
[1,2,3,4]

使用 itertools.combinations_with_replacement 我已经接近了,但我最终得到了跳跃值的列表,例如:

[1,1,1,3]
or
[2,2,2,3]

我不想要这个。我总是想从1开始,递增,直到列表填满,再递增到下一个值。

如果我使用的是 itertools,那么有没有办法删除我不想要的列表?

感觉验证 combinations 的结果比简单地创建您需要的那些列表更费力。

这可以通过递归函数来完成,该函数在每一步中添加要添加到列表中的值,直到达到定义的大小:

def gen_list(pre, size):
    if size == 1:
        return [pre]

    res = gen_list(pre + [pre[-1]], size - 1)
    res.extend(gen_list(pre + [pre[-1]+1], size-1))
    return res

for l in gen_list([1], 4):
    print(l)

打印:

[1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 2, 2]
[1, 1, 2, 3]
[1, 2, 2, 2]
[1, 2, 2, 3]
[1, 2, 3, 3]
[1, 2, 3, 4]

我不使用组合,而是直接生成模式。

创建具有所需长度的 1 列表并向后迭代,相应地更改列表。

def generate_increment(n):
    lst = [1] * n
    result = []
    for k in range(n-1):
        lst[-1] += 1
        result.append(lst[:])
        for i in range(len(lst)-2, k, -1):
            a, b = lst[i], lst[i+1]
            if a != b:
                lst[i] = b
                result.append(lst[:])
    return result

>>print(*generate_increment(4), sep='\n')

[1, 1, 1, 2]
[1, 1, 2, 2]
[1, 2, 2, 2]
[1, 2, 2, 3]
[1, 2, 3, 3]
[1, 2, 3, 4]