如何找到相邻元素的出现

How to find occurrences of neighboring elements

我编写了一个程序来计算 "11" 在零和一的输入序列(列表)中出现的次数。输出应该return一个数字,也就是"11".

出现的次数

我实现了以下代码:

def count_ones(seq):
   # return the number of occurrences as a number
   return sum(1 for i in seq if i != 0)

print(count_ones([0, 0, 1, 1, 1, 0])) # this should print 2

但它没有按需要工作。我应该怎么做才能改进上面给出的代码?

使用 zip

def count_ones(seq):
    # find pairs where current == next element == 1
    return sum(1 for x, y in zip(seq, seq[1:]) if x == y == 1)

测试

print(count_ones([1, 0, 1])           # Output: 0
print(count_ones([1, 0, 1, 1])        # Output: 1
print(count_ones([0, 0, 1, 1, 1, 0])) # Output: 2