mik*_*iku 8 python range sequence python-itertools
我想创建一个范围(例如(1,5))的数字与一些重复(例如4):
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)
一种方法是写:
list(itertools.chain(*([x] * 4 for x in range(1, 5))))
Run Code Online (Sandbox Code Playgroud)
或类似地:
list(itertools.chain(*(itertools.repeat(x, 4) for x in range(1, 5))))
Run Code Online (Sandbox Code Playgroud)
但是,有一个平坦的步骤,可以避免.
是否有更多的pythonic或更紧凑的版本来生成这样的序列?
您只需使用列表推导即可.
l = [i for i in range(1, 5) for _ in range(4)]
Run Code Online (Sandbox Code Playgroud)
产量
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4]
Run Code Online (Sandbox Code Playgroud)
您的解决方案没有任何问题.但您可以使用chain.from_iterable以避免拆包步骤.
否则,如果您乐意使用第三方库,我唯一的其他推荐是NumPy.
from itertools import chain, repeat
import numpy as np
# list solution
res = list(chain.from_iterable(repeat(i, 4) for i in range(1, 5)))
# NumPy solution
arr = np.repeat(np.arange(1, 5), 4)
Run Code Online (Sandbox Code Playgroud)