方法1: Here'e一种方法使用modulus
产生的循环索引来处理通用序列 -
def cyclic_seq(x, N):
return np.take(x, np.mod(np.arange(N),len(x)))
方法2:出于性能,下面的砖的另一方法间隔的最大数量的多个再利用的slicing
以选择第一N
元素 -
def cyclic_seq_v2(x, N):
return np.tile(x,(N+N-1)//len(x))[:N]
个样品试验 -
In [81]: cyclic_seq([6,9,2,1,7],14)
Out[81]: array([6, 9, 2, 1, 7, 6, 9, 2, 1, 7, 6, 9, 2, 1])
In [82]: cyclic_seq_v2([6,9,2,1,7],14)
Out[82]: array([6, 9, 2, 1, 7, 6, 9, 2, 1, 7, 6, 9, 2, 1])
运行测试
In [327]: x = np.random.randint(0,9,(3))
In [328]: %timeit np.resize(x, 10000) # @Daniel Forsman's solution
...: %timeit list(itertools.islice(itertools.cycle(x),10000)) # @Chris soln
...: %timeit cyclic_seq(x,10000) # Approach #1 from this post
...: %timeit cyclic_seq_v2(x,10000) # Approach #2 from this post
...:
1000 loops, best of 3: 296 µs per loop
10000 loops, best of 3: 185 µs per loop
10000 loops, best of 3: 120 µs per loop
10000 loops, best of 3: 28.7 µs per loop
In [329]: x = np.random.randint(0,9,(30))
In [330]: %timeit np.resize(x, 10000) # @Daniel Forsman's solution
...: %timeit list(itertools.islice(itertools.cycle(x),10000)) # @Chris soln
...: %timeit cyclic_seq(x,10000) # Approach #1 from this post
...: %timeit cyclic_seq_v2(x,10000) # Approach #2 from this post
...:
10000 loops, best of 3: 38.8 µs per loop
10000 loops, best of 3: 101 µs per loop
10000 loops, best of 3: 115 µs per loop
100000 loops, best of 3: 13.2 µs per loop
In [331]: %timeit np.resize(x, 100000) # @Daniel Forsman's solution
...: %timeit list(itertools.islice(itertools.cycle(x),100000)) # @Chris soln
...: %timeit cyclic_seq(x,100000) # Approach #1 from this post
...: %timeit cyclic_seq_v2(x,100000) # Approach #2 from this post
...:
1000 loops, best of 3: 297 µs per loop
1000 loops, best of 3: 942 µs per loop
1000 loops, best of 3: 1.13 ms per loop
10000 loops, best of 3: 88.3 µs per loop
性能,approach #2
似乎合作得非常好。
这是否总是一个1d数组? –
@WillemVanOnsem是 –
发布的解决方案是否适合您? – Divakar