Python,字符串中的特定字符数

Python, specific count of chars in string(Python,字符串中的特定字符数)
本文介绍了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.groupbycollections.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,字符串中的特定字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)