听起来您正在寻找itertools.product
. 我相信这会满足您的要求:
def seq(s):
length = 1
while True:
for p in itertools.product(s, repeat=length):
yield p
length += 1
现在您可以执行以下操作:
>>> zip(range(10), seq(set((1, 2, 3))))
[(0, (1,)), (1, (2,)), (2, (3,)), (3, (1, 1)), (4, (1, 2)),
(5, (1, 3)), (6, (2, 1)), (7, (2, 2)), (8, (2, 3)), (9, (3, 1))]
或这个:
>>> test_seq = itertools.izip(itertools.count(), seq(set((1, 2, 3))))
>>> for i in range(10):
... next(test_seq)
...
(0, (1,))
(1, (2,))
(2, (3,))
(3, (1, 1))
(4, (1, 2))
(5, (1, 3))
(6, (2, 1))
(7, (2, 2))
(8, (2, 3))
(9, (3, 1))
这也可以使用 other 进一步压缩itertools
:
>>> from itertools import chain, product, count
>>> s = set((1, 2, 3))
>>> test_seq = chain.from_iterable(product(s, repeat=n) for n in count(1))
>>> zip(range(10), test_seq)
[(0, (1,)), (1, (2,)), (2, (3,)), (3, (1, 1)), (4, (1, 2)), (5, (1, 3)),
(6, (2, 1)), (7, (2, 2)), (8, (2, 3)), (9, (3, 1))]