简体   繁体   中英

counting occurrence of consecutive elements in a list (python)

Given a list

a=['g','d','r','x','s','g','d','r']

I want to count for example the occurrence of gdr, so I would apply some function a.function('g','d','r') and return 2 to me (because gdr occurred 2 times).

You can do that as:

def get_occur(list, seq):
    return ''.join(list).count(''.join(seq))

>>> get_occur(['a', 's', 'a', 's'], ['a', 's'])
2

If you are passing in strings, you can do:

return your_string.count(pattern)

If they are only strings in the list, you can join them in a long string and use its count method:

>>> a=['g','d','r','x','s','g','d','r']
>>> ''.join(a).count('gdr')
2

If you have a mix of strings and numbers for example, you may use map(str,a) before joining and the method would still work:

>>> a=[1,13,4,2,1,13,4]
>>> ''.join(map(str,a)).count('1134')
2

If you need all this packed in a function, you can have something like this:

def count_pattern(lst, *pattern):
    return ''.join(l).count(''.join(pattern))

And will be able to call it: count_pattern(a, 'g', 'd', 'r') or count_pattern(a, 'gdr') or even count_pattern(a, 'gd', 'r') .

What about:

>>> a=['g','d','r','x','s','g','d','r']
>>> print "".join(a).count("gdr")
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM