快速生成条件为 Python 的序列

Fast generating sequences with conditions in Python

我正在寻找 [a, b, c] 形式的数字序列的所有组合,其中 a, b, c 可以从集合 (0,1,2) 中取值并满足以下条件每个下一个元素都大于或等于他的前一个元素。当然我可以用动物的方式来做,比如:

import itertools

for i in itertools.product(range(0,3), repeat=3):
    if i[0]<=i[1] and i[1]<=i[2]:
        print (i)

输出:

(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 1)
(0, 1, 2)
(0, 2, 2)
(1, 1, 1)
(1, 1, 2)
(1, 2, 2)
(2, 2, 2)

但是,我想做得比猴子更聪明,因为我实际上要处理更大的序列。如何在保持分步组合生成结构的情况下做得更好?

我认为您可以使用 itertools 中的另一个函数来完成这项工作:

import itertools

t = [0,1,2]
comb = itertools.combinations_with_replacement(t, 3)

for c in comb:
    print(c)