python - 如何从Python中的特定点开始Itertools循环?

标签 python loops python-itertools

我使用下面的代码为英语字母表创建了一个 itertools 循环,

lowercase_letters_cycle = itertools.cycle(string.ascii_lowercase)

如果我在此迭代器对象上运行 for 循环,则第一次迭代将给出“a”作为输出,因为循环从“a”开始。我怎样才能使循环从我选择的任何字母开始?

一种有效的方法是,

def start_cycle(letter):
  lowercase_letters_cycle = itertools.cycle(lowercase_letters)
  letter_index = lowercase_letters.index(letter)
  index = 0

  while True:
    if index == letter_index:
      break

    letter = next(lowercase_letters_cycle)
    index += 1

  return lowercase_letters_cycle

但是有没有更短的方法呢?

最佳答案

itertools 文档提供了 recipe用于消耗迭代器中的多个项目。

from itertools import islice
import collections


def consume(iterator, n=None):
    "Advance the iterator n-steps ahead. If n is None, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

因此,您创建了循环,然后在继续之前消耗了一些它。

lowercase_letters_cycle = itertools.cycle(string.ascii_lowercase)

consume(lowercase_letters_cycle, ord('n') - ord('a'))

assert next(lowercase_letters_cycle) == 'n')

同样的consume也可以从 third-party more-itertools package 获得。 .

关于python - 如何从Python中的特定点开始Itertools循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71970948/

相关文章:

python - 查找对(连接)的组合

python - 混合隐式和显式等待

python - PyCharm 中类 'objects' 的未解析属性引用 ''

Python。结果不正确

r - 基于R中的移动时间窗口加入数据

javascript - for循环每5次迭代递增变量?

python - pandas 应用参数没有 lambda 的函数

javascript - 保持 jQuery 动画循环

Python itertools.combinations 的结果

python - 折叠列表列表,按特定元素分组并附加其他元素