考虑一下这个系列:
s = [1, -1, 1, 1, 1, -1]
计算此类序列中值变化的次数最省时的方法是什么?在此示例中,答案为 3(从 1 到 -1,再回到 1,再到 -1)
我将使用numpy
numpy
(np.diff(s)!=0).sum() Out[497]: 3