使用列表方法:

sentence = 'when I was young I would listen to the radio waiting for my favorite songs'
char_counts = []
for char in sentence:
    char_counts.append((char, sentence.count(char)))
char_counts = list(set(char_counts))
char_counts.sort(key=lambda x: x[1], reverse=True)
for char in char_counts:
    print(char[0], char[1])

使用字典方法:

sentence = 'when I was young I would listen to the radio waiting for my favorite songs'
char_counts = {}
for char in sentence:
    if char not in char_counts:
        char_counts[char] = sentence.count(char)
char_counts = sorted(char_counts.items(), key=lambda x: x[1], reverse=True)
for char in char_counts:
    print(char[0], char[1])
统计英文句子中字符出现次数的两种方法:列表和字典

原文地址: https://www.cveoy.top/t/topic/ndrF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录