【问题标题】:Count occurrence of all letters in string (python) [duplicate]计算字符串中所有字母的出现次数(python)[重复]
【发布时间】:2021-08-04 11:58:32
【问题描述】:

我有一个给定的消息:

message = """Nhpbz Qbspbz Jhlzhy dhz h Yvthu nlulyhs huk zahalzthu dov wshflk h jypapjhs yvsl pu aol lcluaz aoha slk av aol kltpzl vm aol Yvthu Ylwbispj huk aol ypzl vm aol Yvthu Ltwpyl.""" 

我想计算所有字母的出现次数(从 a 到 z)。我知道怎么写一封信:

def count_letters(message, char):

    return sum(char == c for c in message)

print(count_letters(message, 'a'))

有没有一种方法可以打印所有字母而不必打印每个字母?

【问题讨论】:

    标签: python count letter


    【解决方案1】:

    您可以使用collections.Counter()

    from collections import Counter
    str_count = Counter(message)
    print(str(str_count))
    

    或者如果你想使用循环:

    str_count = {}
    
    for i in message:
        if i in str_count:
            str_count[i] += 1
        else:
            str_count[i] = 1
    
    print(str(str_count)
    

    更多pythonic方式:

    str_count = {i : message.count(i) for i in set(message)}
    
    print(str(str_count)
    

    【讨论】:

      猜你喜欢
      • 2013-11-04
      • 2015-12-01
      • 1970-01-01
      • 2020-06-02
      • 2012-05-31
      • 2011-03-02
      • 1970-01-01
      相关资源
      最近更新 更多