Duplicate each member in an iterator

时光毁灭记忆、已成空白 提交于 2020-07-05 12:55:50

问题


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]


来源:https://stackoverflow.com/questions/36002647/duplicate-each-member-in-an-iterator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!