用Python统计字符串中各字符的个数


#方式一:
def count_str(s):
    adict = {}
for x in str:
if x not in adict:
adict[x] = 1
else:
adict[x] += 1
return adict
#方式二:
# def count_str02(s):
# adict = {}
# for i in str:
# adict[i] = str.count(i)
# return adict
str = "3332222333444444aaabbbbcccdde9999999999999999999999999999”
print(count_str(str))
# print(count_str02(str))

-------------------------------------------------------------------------
控制台输出:
{'3': 6, '2': 4, '4': 6, 'a': 3, 'b': 4, 'c': 3, 'd': 2, 'e': 1, '9': 28}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM