肯定有更多的 numpythonic 做事方式。一种可能性可能是这样的:
import numpy as np
from numpy.lib.stride_tricks import as_strided
def concatenated_ranges(ranges_list) :
ranges_list = np.array(ranges_list, copy=False)
base_range = np.arange(ranges_list.max())
base_range = as_strided(base_range,
shape=ranges_list.shape + base_range.shape,
strides=(0,) + base_range.strides)
return base_range[base_range < ranges_list[:, None]]
如果您只连接几个范围,那么 E 先生的纯 python 解决方案可能是您的最佳选择,但如果您要连接的范围甚至只有 100 个,那么这颗星的速度明显更快。为了比较,我使用了从其他答案中提取的这两个函数:
def junuxx(a) :
b = np.array([], dtype=np.uint8)
for x in a:
b = np.append(b, np.arange(x))
return b
def mr_e(a) :
return reduce(lambda x, y: x + range(y), a, [])
以下是一些时间安排:
In [2]: a = [2, 1, 4, 0 ,2] # the OP's original example
In [3]: concatenated_ranges(a) # show it works!
Out[3]: array([0, 1, 0, 0, 1, 2, 3, 0, 1])
In [4]: %timeit concatenated_ranges(a)
10000 loops, best of 3: 31.6 us per loop
In [5]: %timeit junuxx(a)
10000 loops, best of 3: 34 us per loop
In [6]: %timeit mr_e(a)
100000 loops, best of 3: 2.58 us per loop
In [7]: a = np.random.randint(1, 10, size=(10,))
In [8]: %timeit concatenated_ranges(a)
10000 loops, best of 3: 27.1 us per loop
In [9]: %timeit junuxx(a)
10000 loops, best of 3: 79.8 us per loop
In [10]: %timeit mr_e(a)
100000 loops, best of 3: 7.82 us per loop
In [11]: a = np.random.randint(1, 10, size=(100,))
In [12]: %timeit concatenated_ranges(a)
10000 loops, best of 3: 57.4 us per loop
In [13]: %timeit junuxx(a)
1000 loops, best of 3: 756 us per loop
In [14]: %timeit mr_e(a)
10000 loops, best of 3: 149 us per loop
In [15]: a = np.random.randint(1, 10, size=(1000,))
In [16]: %timeit concatenated_ranges(a)
1000 loops, best of 3: 358 us per loop
In [17]: %timeit junuxx(a)
100 loops, best of 3: 9.38 ms per loop
In [18]: %timeit mr_e(a)
100 loops, best of 3: 8.93 ms per loop