在一个序列中计算数值改变的次数

3

考虑以下数列:

s = [1, -1, 1, 1, 1, -1]

在这样的系列中,计算值改变的次数最高效的方法是什么?在这个例子中,答案是3(从1到-1,返回到1,再到-1)

3个回答

5

我将使用 numpy 库。

(np.diff(s)!=0).sum()
Out[497]: 3

非常简洁完美。再次感谢。 - Saeed

2

使用numpy的另一种解决方案是:

最初的回答

np.count_nonzero(np.diff(s))

一个原生的Python解决方案是

sum(s[i - 1] != s[i] for i in range(1, len(s)))

1

我会选择这个,如果有错请纠正..!:)

# This will append 1 in list if change occurs
c = [1 for i,x in enumerate(s[:-1]) if x!= s[i+1] ]  
# Printing the length of list which is ultimately the total no. of change
print(len(c))

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接