Python,字符串中的特定字符数
问题描述
我正在尝试计算 python 中字符串中出现的次数.我想采用二进制输入,例如001101".然后数出 1、0、11、00 等的个数.
I am trying to count the number of occurrences in a string in python. I would like to take a binary input, say '001101'. Then count the number of 1s, 0s, 11s, 00s etc.
我试图通过使用计数来实现这一点,但这将输出有 3 个 1,当我只希望它输出 1 个 1 和 1 个 11 并且它不单独计算它们时,除非它们在它们的拥有.
I have tried to implement this by using count, but this will output that there are 3 1s, when i only want it to output 1 1, and 1 11s and for it to not count them individually, unless they are on their own.
我也试过用 find 来实现这个,但我遇到了同样的问题.
I have also tried to implement this with find, but i am having the same problem.
任何帮助将不胜感激,谢谢.
Any help would be appreciated, thanks.
解决方案
您可以使用 itertools.groupby
和 collections.Counter
:
You can do the following, using itertools.groupby
and collections.Counter
:
from itertools import groupby
from collections import Counter
s = '001101011'
c = Counter(''.join(g) for _, g in groupby(s))
c.get('11')
# 2
c.get('1')
# 1
c.get('111', 0) # use default value to capture count 0 properly
# 0
这会将字符串分组为仅由相等字符组成的子字符串,并对这些子字符串执行计数.
This groups the string into substrings consisting only of equal chars and performs the counting on those substrings.
相关文章