简体   繁体   English

如何使用itertools重复每个Python列表的元素n次?

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

I have a list with numbers: numbers = [1, 2, 3, 4] . 我有一个数字列表: numbers = [1, 2, 3, 4]

I would like to have a list where they repeat n times like so (for n = 3 ): 我想有一个列表,他们重复这样的n次(对于n = 3 ):

[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4] . [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. 问题是我只想使用itertools ,因为我的性能非常受限制。

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? 有没有办法只使用itertools ,而不使用排序,循环和列表推导? The closest I could get is: 我能得到的最接近的是:

list(itertools.chain.from_iterable([itertools.repeat(i, 3) for i in numbers])) , 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. 但它也使用列表理解,我想避免。

Since you don't want to use list comprehension, following is a pure (+ zip ) itertools method to do it - 由于您不想使用列表推导,以下是一个纯(+ zipitertools方法来执行此操作 -

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]

Firstly, using functions from itertools won't necessarily be faster than a list comprehension — you should benchmark both approaches. 首先,使用来自itertools函数不一定比列表理解更快 - 你应该对这两种方法进行基准测试。 (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 : chain.from_iterable()生成器表达式一起使用

>>> 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]

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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM