本文介绍了Python,字符串中字符的特定计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算python中字符串中出现的次数。我想输入一个二进制输入,例如 001101。然后计算1s,0s,11s,00s等的数目。我只希望它输出1 1和1 11s,并且不让它们单独计数,除非它们是单独存在的。



我也尝试实现此功能找到,但是我遇到了同样的问题。



任何帮助将不胜感激,谢谢。

解决方案

您可以使用和:

 从itertools导入groupby 
从集合导入计数器

s ='001101011'
c = Counter(''。joinby(g)for _,g in groupby(s)

c.get('11')
#2
c.get('1')
#1
c.get('111',0)#使用默认值正确捕获计数0
#0

这会将字符串分组为仅包含相等字符的子字符串,并对这些子字符串执行计数。


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.

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.

I have also tried to implement this with find, but i am having the same problem.

Any help would be appreciated, thanks.

解决方案

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,字符串中字符的特定计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:47