计算每个字符出现的次数

学习笔记,日后温习

计算每个字符的出现次数,并按照出现的顺序将其作为元组列表返回。

例如,给你一个字符串“abracadabra”,输出为

ordered_counted("abracadabra") ==[('a',5),('b',2),('r',2),('c',1),('d',1)]
解法一:


x="avfasedaggg"
def ordered_count(x):
    
    #定义一个空集合
    e={}                
    for i in x:
        e[i]=x.count(i)
#     print(e)
    #输出{'g': 3, 's': 1, 'v': 1, 'e': 1, 'f': 1, 'a': 3, 'd': 1}   结果为字典,并不是要求的元组列表
    
    #定义一个空列表
    ls1=[]
    #键值在字典中遍历
    for key in e:
        #将字典中键值对,改写到了元组中
        t=(key,e[key])
        #将元组添加到列表中
        ls1.append(t)
        
    #返回元组列表
    return ls1 
    
    
ordered_count(x)
#输出为[('g', 3), ('s', 1), ('v', 1), ('e', 1), ('f', 1), ('a', 3), ('d', 1)]

解法二:


def ordered_count(string):
    #set去重
    list_set=set(string)
    #准备空列表
    list_out=[]
    #用不重复的遍历循环
    for i in list_set:
        #用原始字符串计数
        list_out.append((i,string.count(i)))
    #返回元组列表
    return list_out
    
string='abracadabra'
ordered_count(string)
解法三

def ordered_count(s):
    counts=list(set([(c,s.count(c)) for c in s]))
    return sorted(list(counts),key=lambda x: x[1],reverse=True)

s='abracadabra'
ordered_count(s)
#输出为[('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]

猜你喜欢

转载自blog.csdn.net/weixin_42610407/article/details/87555217