编程题:统计字符串中字符出现的次数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dengNDSC/article/details/78786550

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)

猜你喜欢

转载自blog.csdn.net/dengNDSC/article/details/78786550
今日推荐