分别用列表以及字典的方法统计统计英文句子"when I was young I would listen to the radio waiting for my favorite songs"中各字符出现的次数并按序输出。
时间: 2024-05-01 21:18:34 浏览: 81
统计字符出现的次数
5星 · 资源好评率100%
好的,这是一个关于 Python 数据结构的问题。我可以给您答案。
使用列表统计:
```
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 not in char_count:
char_count.append(char_list.count(char))
# 输出结果
for i in range(len(char_count)):
print(char_list[i], "出现次数为:", char_count[i])
```
使用字典统计:
```
sentence = "when I was young I would listen to the radio waiting for my favorite songs"
char_dict = {}
# 统计各字符的出现次数
for char in sentence:
if char in char_dict:
char_dict[char] += 1
else:
char_dict[char] = 1
# 按序输出结果
for key in sorted(char_dict):
print(key, "出现次数为:", char_dict[key])
```
希望这能解决您的问题。如果您有更多的问题,请直接问我。
阅读全文