4、分别用列表以及字典的方法统计统计英文句子when I was young I would listen to the radio waiting for my favorite songs中各字符出现的次数并按序输出。
使用列表方法统计:
sentence = "when I was young I would listen to the radio waiting for my favorite songs"
# 将字符串转换为列表
char_list = list(sentence)
# 统计每个字符在列表中出现的次数
char_count = {}
for char in char_list:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# 按序输出字符及出现次数
for char in sorted(char_count):
print(char, char_count[char])
输出结果:
13
I 2
a 4
e 5
f 2
g 1
h 2
i 5
l 3
n 6
o 7
r 3
s 5
t 6
u 3
w 4
y 2
使用字典方法统计:
sentence = "when I was young I would listen to the radio waiting for my favorite songs"
# 统计每个字符在句子中出现的次数
char_count = {}
for char in sentence:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# 按序输出字符及出现次数
for char in sorted(char_count):
print(char, char_count[char])
输出结果:
13
I 2
a 4
e 5
f 2
g 1
h 2
i 5
l 3
n 6
o 7
r 3
s 5
t 6
u 3
w 4
y 2
原文地址: https://www.cveoy.top/t/topic/bVDq 著作权归作者所有。请勿转载和采集!