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

来源:互联网 发布:神秘的程序员 头像 编辑:程序博客网 时间:2024/06/06 10:12

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

# -*- coding: utf-8 -*import sys,localereload(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))

这里写代码片