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,字符串中的特定字符数


- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01