How to repeat each of a Python list's elements n times with itertools only?

浪子不回头ぞ 提交于 2019-12-07 14:50:03

问题


I have a list with numbers: numbers = [1, 2, 3, 4].

I would like to have a list where they repeat n times like so (for n = 3):

[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4].

The problem is that I would like to only use itertools for this, since I am very constrained in performance.

I tried to use this expression:

list(itertools.chain.from_iterable(itertools.repeat(numbers, 3)))

But it gives me this kind of result:

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

which is obviously not what I need.

Is there a way to do this with itertools only, without using sorting, loops and list comprehensions? The closest I could get is:

list(itertools.chain.from_iterable([itertools.repeat(i, 3) for i in numbers])),

but it also uses list comprehension, which I would like to avoid.


回答1:


Since you don't want to use list comprehension, following is a pure (+zip) itertools method to do it -

from itertools import chain, repeat

list(chain.from_iterable(zip(*repeat(numbers, 3))))
# [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]



回答2:


Firstly, using functions from itertools won't necessarily be faster than a list comprehension — you should benchmark both approaches. (In fact, on my machine it's the opposite).

Pure list comprehension approach:

>>> numbers = [1, 2, 3, 4]
>>> [y for x in numbers for y in (x,)*3]
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

Using chain.from_iterable() with a generator expression:

>>> from itertools import chain, repeat
>>> list(chain.from_iterable(repeat(n, 3) for n in numbers))
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]



回答3:


Think you were very close, just rewriting the comprehension to a generator:

n = 3
numbers = [1, 2, 3, 4]
list(itertools.chain.from_iterable((itertools.repeat(i, n) for i in numbers)))


来源:https://stackoverflow.com/questions/45799233/how-to-repeat-each-of-a-python-lists-elements-n-times-with-itertools-only

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