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

发布于 2025-01-23 04:49:07 字数 587 浏览 0 评论 0原文

我已经使用以下代码为英语字母创建了一个itertools循环,

lowercase_letters_cycle = itertools.cycle(string.ascii_lowercase)

如果我在此迭代对象上运行循环 loop,则第一个迭代会给我“ 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

但是有任何较短的方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

深海蓝天 2025-01-30 04:49:07

itertools文档提供A 用于从迭代器中食用许多项目。

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')

相同的消费也可以从第三方更多 - itertools软件包

The itertools documentation supplies a recipe for consuming a number of items from an iterator.

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)

So you create the cycle, then just consume a bit of it before proceeding.

lowercase_letters_cycle = itertools.cycle(string.ascii_lowercase)

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

assert next(lowercase_letters_cycle) == 'n')

The same consume is also available from the third-party more-itertools package.

沉鱼一梦 2025-01-30 04:49:07

您可以从itertools模块中组合ISLICE cyce cyce ,如下所示:

import string 
import itertools

my_it = itertools.islice(itertools.cycle(string.ascii_lowercase), 3, None)

它将产生d(来源的字符在第一个3)之后,然后e,....,然后z,然后a,然后b , 等等。您可以将第二个参数中的数字更改为islice以从不同的字母开始。

You can combine islice and cycle from the itertools module as follows:

import string 
import itertools

my_it = itertools.islice(itertools.cycle(string.ascii_lowercase), 3, None)

It will yield d (the character that comes after the first 3), then e, ...., then z, then a, then b, and so on. You can change the number in the second argument to islice to start from a different letter.

半暖夏伤 2025-01-30 04:49:07

您可以将输入列表切成小块,以从您选择的索引开始。

offset = 10
lowercase_letters = list(string.ascii_lowercase)

#                 offset_index to end       + start to offset_index-1
offset_letters = lowercase_letters[offset:] + lowercase_letters[:offset]
offset_letters_cycle = itertools.cycle(offset_letters)

然后,

for i in range(10):
    print(next(offset_letters_cycle), end=" ")

打印:

k l m n o p q r s t 

You could just slice the input list to start at the index of your choice.

offset = 10
lowercase_letters = list(string.ascii_lowercase)

#                 offset_index to end       + start to offset_index-1
offset_letters = lowercase_letters[offset:] + lowercase_letters[:offset]
offset_letters_cycle = itertools.cycle(offset_letters)

Then,

for i in range(10):
    print(next(offset_letters_cycle), end=" ")

prints:

k l m n o p q r s t 
最近可好 2025-01-30 04:49:07

import string
from itertools import cycle, dropwhile

def start_cycle(letter):
    return dropwhile(lambda x: x!= letter, cycle(string.ascii_lowercase))

itertools.drophiles.dropwhiles.dropwhile 其前哨功能的效果结果 - 在这种情况下,lambda x:x!= letter,并将“吞咽”结果,直到函数首次返回false。那时
该功能不再被调用,并且可以进行,从而产生任何
进一步的值。

另外,请注意,无需将ascii_lowercase转换为列表,
因为字符串已经是迭代的。

请记住,如果通过ASCII_LOWERCASE中的字符,这将陷入100%CPU的无限循环中。最好用一张检查:


def start_cycle(letter):
    if letter not in string.ascii_lowercase:
         raise ValueError()
    return dropwhile(lambda x: x!= letter, cycle(string.ascii_lowercase))


import string
from itertools import cycle, dropwhile

def start_cycle(letter):
    return dropwhile(lambda x: x!= letter, cycle(string.ascii_lowercase))

itertools.dropwhile will feed the iterable results to its sentinel function - in this case lambda x: x != letter, and will "swallow" the results until the function returns False for the first time. At that point
the function is no longer called, and the iterable proceeds, yielding any
further values.

Also, note there is no need to convert ascii_lowercase to a list,
as strings are already iterables.

Keep in mind that this will run into an infinite loop with 100% CPU if a character not in ascii_lowercase is passed. It is better to guard it with a check:


def start_cycle(letter):
    if letter not in string.ascii_lowercase:
         raise ValueError()
    return dropwhile(lambda x: x!= letter, cycle(string.ascii_lowercase))

如日中天 2025-01-30 04:49:07

如果您只想从特定点开始浏览列表,则可以这样做:

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
start_index = 4

for i in my_list[start_index:]+my_list[:start_index]:
    print(i)

If you just want to run through a list once starting at a particular point you can do:

my_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
start_index = 4

for i in my_list[start_index:]+my_list[:start_index]:
    print(i)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文