从数组中选择项目

时间:2014-11-17 16:40:28

标签: 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_indices[0][i] != (min_indices[0][i-1] + 1)):
        start_indices.append(min_indices[i])
print start_indices

3 个答案:

答案 0 :(得分:3)

你没有增加“i”,我可以告诉你。

答案 1 :(得分:3)

使用列表理解:

>>> 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]

答案 2 :(得分:3)

您可以在numpy.diff使用numpy.where

>>> 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])