Skip to content Skip to sidebar Skip to footer

Counting Sublists In A List

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

Solution 1:

>>>L = [2,4,5,6,2,1,6,6,3,2,4,5,3,4,5]>>>s = [2,4,5]
>>>sum(1for i inrange(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 inrange(len(L)))
2

Solution 2:

x=0for i in range(len(L)):
    if L[i:i+len(s)]==s:
        x+=1

or make it list-comprehension:

len([Nonefor i inrange(len(L)) if L[i:i+len(s)]==s])

Post a Comment for "Counting Sublists In A List"