Reputation: 97
L=[2,4,5,6,2,1,6,6,3,2,4,5,3,4,5]
I want to know how many times an arbitrary sub-sequence shows up, s=[2,4,5]
for instance would return 2 times.
I tried L.count(s)
but it does not work because I think it is expecting to look for something like [random numbers ... [2,4,5] ... random numbers]
instead of 2,4,5
without the brackets.
Upvotes: 3
Views: 5204
Reputation: 34116
>>> L = [2,4,5,6,2,1,6,6,3,2,4,5,3,4,5]
>>> s = [2,4,5]
>>> sum(1 for i in range(len(L)) if L[i:i+len(s)]==s)
2
Almost the same thing, slightly shorter (uses the fact that True
can behave like the number 1
):
>>> sum(L[i:i+len(s)]==s for i in range(len(L)))
2
Upvotes: 5
Reputation: 21615
x=0
for i in range(len(L)):
if L[i:i+len(s)]==s:
x+=1
or make it list-comprehension:
len([None for i in range(len(L)) if L[i:i+len(s)]==s])
Upvotes: 0