从itertools.product对象

时间:2018-08-03 18:12:30

标签: python itertools

我正在使用python itertools模块从aaa迭代到ccc 我不知道从某个位置开始迭代的方法 例如,如果输入是aba,则迭代将从该位置继续 这是我的代码现在的样子: 请注意我使用python 3

from itertools import product
strings = itertools.product(*["abc"]*3)
for item in strings:
    print("".join(item))

1 个答案:

答案 0 :(得分:0)

此方法不会跳过任何计算,它只会丢弃值,直到看到要查找的值为止。这对任何可迭代的方法都适用,但是可能有一个product特定的解决方案,使您可以跳过生成不需要的值。

from itertools import dropwhile, product

def resume(iterable, sentinel):
    yield from dropwhile(lambda x: x != sentinel, iterable)

for t in resume(product('abc', repeat=3), ('a', 'b', 'a')):
    print(*t)