我有一个值数组,x.给定'start'和'stop'索引,我需要使用x的子数组构造一个数组y.
import numpy as np
x = np.arange(20)
start = np.array([2, 8, 15])
stop = np.array([5, 10, 20])
nsubarray = len(start)
Run Code Online (Sandbox Code Playgroud)
当我想Ÿ为:
y = array([ 2, 3, 4, 8, 9, 15, 16, 17, 18, 19])
Run Code Online (Sandbox Code Playgroud)
(实际上我使用的数组要大得多).
构造y的一种方法是使用列表推导,但之后需要将列表展平:
import itertools as it
y = [x[start[i]:stop[i]] for i in range(nsubarray)]
y = np.fromiter(it.chain.from_iterable(y), dtype=int)
Run Code Online (Sandbox Code Playgroud)
我发现使用for循环实际上更快:
y = np.empty(sum(stop - start), dtype = int)
a = 0
for i in range(nsubarray):
b = …Run Code Online (Sandbox Code Playgroud)