仅使用 itertools 重复可迭代对象(可以是无限的)中的每个元素
Repeat each element in an iterable (which can be infinite) using itertools only
下面是否有更简单的表达式,可以使用 itertools
而不需要定义函数?
它必须支持任何可迭代对象,包括来自生成器的无限序列。
我查看了 https://docs.python.org/3/library/itertools.html 中的食谱,没有发现任何明显的东西。
def repeat_each(iterable, n):
"""Repeat each element in iterable n times"""
it = iter(iterable)
for element in it:
for _ in range(n):
yield element
a = itertools.cycle('abcd')
b = repeat_each(a, 4)
print(''.join(itertools.islice(b, 30)))
# Output: 'aaaabbbbccccddddaaaabbbbccccdd'
我不确定它是否涵盖了您想到的所有情况,但您可以使用 tee
(将迭代器复制 n
次)然后 zip
和 chain
它:
from itertools import tee, chain, cycle, islice
a = cycle('abcd')
b = chain.from_iterable(zip(*tee(a, 4)))
print(''.join(islice(b, 30)))
结果:
aaaabbbbccccddddaaaabbbbccccdd
下面是否有更简单的表达式,可以使用 itertools
而不需要定义函数?
它必须支持任何可迭代对象,包括来自生成器的无限序列。
我查看了 https://docs.python.org/3/library/itertools.html 中的食谱,没有发现任何明显的东西。
def repeat_each(iterable, n):
"""Repeat each element in iterable n times"""
it = iter(iterable)
for element in it:
for _ in range(n):
yield element
a = itertools.cycle('abcd')
b = repeat_each(a, 4)
print(''.join(itertools.islice(b, 30)))
# Output: 'aaaabbbbccccddddaaaabbbbccccdd'
我不确定它是否涵盖了您想到的所有情况,但您可以使用 tee
(将迭代器复制 n
次)然后 zip
和 chain
它:
from itertools import tee, chain, cycle, islice
a = cycle('abcd')
b = chain.from_iterable(zip(*tee(a, 4)))
print(''.join(islice(b, 30)))
结果:
aaaabbbbccccddddaaaabbbbccccdd