Python, specific count of chars in string(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.
这篇关于Python,字符串中的特定字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python,字符串中的特定字符数
基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01