在一系列数字上制作重复迭代器?
Making a repeating iterator over a range of digits?
我正在尝试制作一个打印重复序列的迭代器
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, ...
我想要一个迭代器,这样我就可以使用 .next(),并且我希望在迭代器为 9 时调用 .next() 时它循环到 0。
但问题是我可能会有很多这样的东西,所以我不想只做 itertools.cycle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
。
我不想在内存中有那么多相同序列的重复列表。我宁愿在每个迭代器中都有函数 x + 1 % 10 并且每次调用 next 时只让迭代器递增 x。我似乎无法弄清楚如何使用 itertools 来做到这一点。有没有一种 pythonic 的方式来做到这一点?
您可以像这样使用自定义生成器:
def single_digit_ints():
i = 0
while True:
yield i
i = (i + 1) % 10
for i in single_digit_ints():
# ...
您可以编写一个使用 range
的生成器
def my_cycle(start, stop, step=1):
while True:
for x in range(start, stop, step):
yield x
c = my_cycle(0, 10)
您可以使用自己的自定义生成器:
def cycle_range(xr):
while True:
for x in xr:
yield x
假设您使用 Python 2,请使用:
r = xrange(9)
it1 = cycle_range(xr)
it2 = cycle_range(xr)
为了内存效率。
这是通过 itertools
的一种方式:
import itertools
def counter():
for i in itertools.count(1):
yield i%10
g = counter()
我正在尝试制作一个打印重复序列的迭代器
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, ...
我想要一个迭代器,这样我就可以使用 .next(),并且我希望在迭代器为 9 时调用 .next() 时它循环到 0。
但问题是我可能会有很多这样的东西,所以我不想只做 itertools.cycle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
。
我不想在内存中有那么多相同序列的重复列表。我宁愿在每个迭代器中都有函数 x + 1 % 10 并且每次调用 next 时只让迭代器递增 x。我似乎无法弄清楚如何使用 itertools 来做到这一点。有没有一种 pythonic 的方式来做到这一点?
您可以像这样使用自定义生成器:
def single_digit_ints():
i = 0
while True:
yield i
i = (i + 1) % 10
for i in single_digit_ints():
# ...
您可以编写一个使用 range
def my_cycle(start, stop, step=1):
while True:
for x in range(start, stop, step):
yield x
c = my_cycle(0, 10)
您可以使用自己的自定义生成器:
def cycle_range(xr):
while True:
for x in xr:
yield x
假设您使用 Python 2,请使用:
r = xrange(9)
it1 = cycle_range(xr)
it2 = cycle_range(xr)
为了内存效率。
这是通过 itertools
的一种方式:
import itertools
def counter():
for i in itertools.count(1):
yield i%10
g = counter()