Duplicate each member in an iterator

2020-07-26 10:54发布

问题:

Given an iterator i, I want an iterator that yields each element n times, i.e., the equivalent of this function

def duplicate(i, n):
    for x in i:
        for k in range(n):
            yield x

Is there an one-liner for this?

Related question: duplicate each member in a list - python, but the zip solution doesn't work here.

回答1:

This is my simple solution, if you want to duplicate each element same times. It returns a generator expression, which should be memory efficient.

def duplicate(i, n):
    return (k for k in i for j in range(n))

An example usage could be,

print (list(duplicate(range(1, 10), 3)))

Which prints,

[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9]



回答2:

itertools.chain.from_iterable(itertools.izip(*itertools.tee(source, n)))

Example:

>>> x = (a**2 for a in xrange(5))
>>> list(itertools.chain.from_iterable(itertools.izip(*itertools.tee(x, 3))))
[0, 0, 0, 1, 1, 1, 4, 4, 4, 9, 9, 9, 16, 16, 16]

Another way:

itertools.chain.from_iterable(itertools.repeat(item, n) for item in source)

>>> x = (a**2 for a in xrange(5))
>>> list(itertools.chain.from_iterable(itertools.repeat(item, 3) for item in x))
[0, 0, 0, 1, 1, 1, 4, 4, 4, 9, 9, 9, 16, 16, 16]


回答3:

Use a generator expression:

>>> x = (n for n in range(4))
>>> i = (v for v in x for _ in range(3))
>>> list(i)
[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]