计算Python列表中模式出现的次数

Teo*_*off 5 python list count python-2.7 python-3.x

给定一个模式[1,1,0,1,1]和一个长度为 100 的二进制列表,[0,1,1,0,0,...,0,1]. 我想计算此列表中此模式的出现次数。有没有一种简单的方法可以做到这一点,而无需使用变量跟踪每个索引处的每个项目?

请注意,[...,1, 1, 0, 1, 1, 1, 1, 0, 1, 1,...,0]可能会发生这样的事情,但这应该计为 2 次。

Abh*_*hri 5

使用 join 将您的列表转换为字符串。然后做:

text.count(pattern)
Run Code Online (Sandbox Code Playgroud)

如果您需要计算重叠匹配项,则必须使用正则表达式匹配或定义您自己的函数。

编辑 这里是完整的代码:

def overlapping_occurences(string, sub):
    count = start = 0
    while True:
        start = string.find(sub, start) + 1
        if start > 0:
            count+=1
        else:
            return count

given_list = [1, 1, 0, 1, 1, 1, 1, 0, 1, 1]
pattern = [1,1,0,1,1]

text = ''.join(str(x) for x in given_list)
print(text)
pattern = ''.join(str(x) for x in pattern)
print(pattern)
print(text.count(pattern)) #for no overlapping
print(overlapping_occurences(text, pattern))
Run Code Online (Sandbox Code Playgroud)