Python实现统计字符串中每个字符出现的次数
初学python做一个小测试 , 面试时也可能会被问到 . 废话不多说 , 直接上代码:
方法一:
#1.目标字符串转为列表
ss='abcacadafa'
ll=list(ss)
#2.用一个列表记录总共多少种字符
new_ll=[]
for i in ss:
if i not in new_ll:
new_ll.append(i)
#3.用一个字典记录结果 , 遍历列表 , 求count()
d={}
for i in new_ll:
d[i]=ll.count(i)
print d
方法二:
原文:https://blog.youkuaiyun.com/weixin_42153985/article/details/80577597
def strcount(a):
#定义一个空字典
b={}
# 求出字符串的长度
c=len(a)
i=0
while i<c:
if a[i] in b:
b[a[i]]+=1
else:
b[a[i]]=1
i+=1
#遍历字典
for item in b.items():
print(item)
if __name__ == '__main__':
a="aasdxzs123123sdf"
strcount(a)
```