代码之家  ›  专栏  ›  技术社区  ›  Ahmed Tounsi Chaime

开始从itertools.product对象中的某个位置迭代

  •  0
  • Ahmed Tounsi Chaime  · 技术社区  · 8 年前

    我正在使用python itertools模块创建一个生成器,它从 aaa 到 ccc .

    我想不出从某个位置开始迭代的方法 例如,如果输入是 aba 迭代将从该位置继续 这就是我的代码现在的样子:

    from itertools import product
    
    strings = itertools.product(*["abc"]*3)
    for item in strings:
        print("".join(item))
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Patrick Haugh    8 年前

    此方法不跳过任何计算,它只会删除值,直到看到要查找的值为止。这应该对任何iterable都有效,但是可能有 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)
    
    推荐文章