欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

统计字符串中各字符出现的次数

程序员文章站 2022-04-30 20:38:06
...

1、统计一个字符串中各字符出现的次数
2、统计一个字符串中各字符相邻连续出现的次数

# -*- coding: utf-8 -*
import sys,locale
reload(sys)
sys.setdefaultencoding('utf8')
if __name__=="__main__":
    mystr=raw_input()
    myList=[]
    for i in xrange(len(mystr)):
        myList.append(mystr[i])
    #1、统计一个字符串中各字符出现的次数 abccddeeffmmnnggwwqqgndhgfdzzdxxmfsfghh
    resList=[]
    mySet=set(myList)
    print(u'统计一个字符串中各字符出现的次数:')
    for i in (mySet):
        print ("key:%s value:%d" %(i,myList.count(i)))

    #2、统计一个字符串中各字符相邻连续出现的次数
    j=0
    print(u'统计一个字符串中各字符相邻连续出现的次数:')
    while j<(len(myList)-1):
        count=1
        for k in xrange(j+1,len(myList)):
            if(myList[j]!=myList[k]):
                break
            else:
                count=count+1
        print ("key:%s count:%d" %(myList[j],count))
        j=j+count
    if(myList[len(myList)-1]!=myList[len(myList)-2]):
        count=1
        print ("key:%s count:%d" %(myList[len(myList)-1],count))

统计字符串中各字符出现的次数

相关标签: Python 次数