程式設計題:統計字串中字元出現的次數
阿新 • • 發佈:2018-10-31
1.
from collections import Counter
string = '1212ababABAB'
s = Counter(string)
print(s)
2.
string = '1212ababABAB'
s = {x: string.count(x) for x in set(string)} # 用的是字典推導式和str自帶的str.count方法
print(s)
3.
string = '1212ababABAB'
def fun(s):
# 去除字串中的空格
s = list(''.join(s.split()))
# 去重
s1 = set(s)
l = list(s1)
dic = {}
for a in range(len(l)):
num = 0
for i in reversed(range(len(s))):
if l[a] == s[i]:
num = num + 1
s.pop(i)
dic[l[a]] = num
return dic
t = fun(string)
print(t)