肯定有更多的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]]
如果您串联只有几个范围,那么很可能鄂先生的纯Python的解决方案是您最好的选择,但如果你有即使仅有百范围来连接,这颗恒星明显更快。为了比较我用从其他的答案中提取这两个功能:
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
您能否展示一些更多的代码 - 您从a到b的确切程度如何?最重要的是,[你有什么尝试?](http://whathaveyoutried.com) – 2013-02-26 12:38:10