Python 从数组中选择项

Python 从数组中选择项,python,numpy,Python,Numpy,我尝试获取一个整数数组,例如: [1,2,3,4,9,10,11,12,18,19,20,21]并获得有跳跃的值,因此,我的程序的输出将是[1,9,18]。我用Python编写了以下代码,这似乎要花很长时间才能运行: min_indices = np.where(data[:,1] == data[:,1].min()) start_indices = np.array([0]) i = 1 while (i < len(min_indices[0])): if (min_indi

我尝试获取一个整数数组,例如:

[1,2,3,4,9,10,11,12,18,19,20,21]并获得有跳跃的值,因此,我的程序的输出将是[1,9,18]。我用Python编写了以下代码,这似乎要花很长时间才能运行:

min_indices = np.where(data[:,1] == data[:,1].min())
start_indices = np.array([0])
i = 1
while (i < len(min_indices[0])):
    if (min_indices[0][i] != (min_indices[0][i-1] + 1)):
        start_indices.append(min_indices[i])
print start_indices

您并没有增加我所能知道的i。

使用列表理解:

>>> a=[1,2,3,4,9,10,11,12,18,19,20,21]
>>> [a[i] for i,_ in enumerate(a[1:]) if (a[i]!=a[i-1]+1)]
[1, 9, 18]
并使用zip:

>>> [a[0]]+[i for (i,j) in zip(a[1:],(a[:-1])) if (i!=j+1)]
[1, 9, 18]
您可以在此处使用:


你从不在循环中增加i,这将导致永远运行。谢谢。忘了吧。
>>> a = np.array([1,2,3,4,9,10,11,12,18,19,20,21])
>>> indices = np.where(np.diff(a) > 1)[0] + 1
>>> np.concatenate(([a[0]], a[indices]))
array([ 1,  9, 18])