[Python] How to start Itertools cycle from a particular point in Python?

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I have created an itertools cycle for the English alphabet using the code below,

    lowercase_letters_cycle = itertools.cycle(string.ascii_lowercase)


    If I run a for loop on this iterator object, the first iteration would give me "a" as the output because the cycle starts from "a". How can I make it so that cycle starts from any letter of my choice?

    One way that works is,

    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


    But is there any shorter method?

    Continue reading...

Compartilhe esta Página