1

我有一个从直线渐变派生的整数数组。该数组称为 sign_slope,如下所示:

sign_slope = array([-1, 1, -1, ..., -1, -1, -1])

我正在寻找数组中的连续项为:1、-1 例如,您可以从上面的 sign_slope 输出中看到:sign_slope[1] = 1 和 sign_slope[2] = -1 这将是第一个许多我想检测项目/索引号的情况。在上述情况下,我希望代码输出与第 (n-1) 个索引对应的索引号数组或列表,即 sign_slope[1]。我已经写了以下似乎有效的打印声明。但是,我不知道如何输出索引号而不是当前情况下的值并将它们附加到列表或将它们输入到数组中。

for n in range(0, len(sign_slope)):
    if sign_slope[n] < 0 and sign_slope[n - 1] > 0:
        print sign_slope[n - 1]
    else:
        print 0

谢谢提前,

凯恩

4

2 回答 2

4

在一系列指标上循环通常被认为是非常不合常规的。它读起来很糟糕,掩盖了你真正想要做的事情。因此,找到子列表的更好解决方案是循环使用enumerate()内置函数来获取值旁边的索引。我们还可以提供更通用的解决方案,并使其成为易于使用的生成器。

def find_sublists(seq, sublist):
    length = len(sublist)
    for index, value in enumerate(seq):
        if value == sublist[0] and seq[index:index+length] == sublist:
            yield index

我们在这里所做的是遍历列表,获取值与子列表开头匹配的索引。然后我们检查列表的那个段是否与我们的子列表匹配,如果匹配,我们yield就索引。这使我们能够快速找到列表中所有匹配的子列表。

然后我们可以像这样使用它,使用list内置函数从生成器创建一个列表:

>>> list(find_sublists([-1, 1, -1, -1, -1, 1, -1], [1, -1]))
[1, 5]
于 2012-10-18T10:25:14.543 回答
0

sign_slope假设您的数组是一个数组,您可以在不编写循环的情况下执行此操作numpy

import numpy as np

# some data
sign_slope = np.array([-1, 1, -1, 1, 1, -1, -1])

# compute the differences in s
d = np.diff(sign_slope)

# compute the indices of elements in d that are nonzero
pos = np.where(d != 0)[0]

# elements pos[i] and pos[i]+1 are the indices
# of s that differ:
print s[pos[i]], s[pos[i]+1]

这是一个显示变量值的 ipython 会话:

In [1]: import numpy as np

In [2]: s = np.array([-1, 1, -1, 1, 1, -1, -1])

In [3]: d = np.diff(s)

In [4]: print d
[ 2 -2  2  0 -2  0]

In [5]: pos = np.where(d != 0)[0]

In [6]: print pos
[0 1 2 4]

In [7]: print s[pos[0]], s[pos[0]+1]
-1 1

In [8]: print s[pos[1]], s[pos[1]+1]
1 -1

In [9]: print s[pos[2]], s[pos[2]+1]
-1 1

In [10]: print s[pos[3]], s[pos[3]+1]
1 -1

希望这可以帮助

编辑:实际上,回想起来,我错过了一些差异。我会回复你的。很抱歉有任何混淆。

编辑2:固定,我犯了一个愚蠢的错误。

于 2012-10-18T10:41:23.100 回答