如何无休止地重启字符串迭代器?
How can I restart a string iterator endlessly?
这个问题与this, this, and this一个有点相关。假设我有两个不同长度的 generators/iterators:
>>> s = "abcde"
>>> r = range(0, 16)
我现在想重复迭代较短的,直到用完较长的。标准 zip()
函数在两者中较短的一个用完后终止:
>>> for c, i in zip(s, r) :
... print(c, i)
...
a 0
b 1
c 2
d 3
e 4
我能想到的最好办法是将字符串包装到生成器中,如下所示:
>>> def endless_s(s) :
... while True :
... for c in s :
... yield c
这给了我想要的结果
>>> _s = endless_s(s)
>>> for c, i in zip(_s, r) :
... print(c, i)
...
a 0
b 1
c 2
d 3
e 4
a 5
b 6
c 7
d 8
e 9
a 10
b 11
c 12
d 13
e 14
a 15
现在我想知道:有没有更好更紧凑的方法呢?像无尽的字符串连接,或类似的东西?
你可以用 itertools.cycle
:
Make an iterator returning elements from the iterable and saving a
copy of each. When the iterable is exhausted, return elements from the
saved copy. Repeats indefinitely.
能够完全取代你的功能:
from itertools import cycle as endless_s
这个问题与this, this, and this一个有点相关。假设我有两个不同长度的 generators/iterators:
>>> s = "abcde"
>>> r = range(0, 16)
我现在想重复迭代较短的,直到用完较长的。标准 zip()
函数在两者中较短的一个用完后终止:
>>> for c, i in zip(s, r) :
... print(c, i)
...
a 0
b 1
c 2
d 3
e 4
我能想到的最好办法是将字符串包装到生成器中,如下所示:
>>> def endless_s(s) :
... while True :
... for c in s :
... yield c
这给了我想要的结果
>>> _s = endless_s(s)
>>> for c, i in zip(_s, r) :
... print(c, i)
...
a 0
b 1
c 2
d 3
e 4
a 5
b 6
c 7
d 8
e 9
a 10
b 11
c 12
d 13
e 14
a 15
现在我想知道:有没有更好更紧凑的方法呢?像无尽的字符串连接,或类似的东西?
你可以用 itertools.cycle
:
Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.
能够完全取代你的功能:
from itertools import cycle as endless_s