分别用列表以及字典的方法统计统计英文句子"when I was young I would listen to the radio waiting for my favorite songs"中各字符出现的次数并按序输出。
时间: 2024-05-16 07:12:09 浏览: 29
统计字符出现的次数
5星 · 资源好评率100%
好的,您提出的问题是关于Python编程的。以下是使用列表和字典分别统计英文句子出现次数的示例代码:
使用列表统计出现次数:
```
sentence = "when I was young I would listen to the radio waiting for my favorite songs"
char_list = list(sentence)
count_list = []
for char in char_list:
count_list.append(char_list.count(char))
print("字符\t次数")
for i in range(len(char_list)):
print("{}\t{}".format(char_list[i], count_list[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 not in char_dict:
char_dict[char] = 1
else:
char_dict[char] += 1
print("字符\t次数")
for char, count in char_dict.items():
print("{}\t{}".format(char, count))
```
希望能够帮助您解决问题!如果您还有其他问题,欢迎随时问我。
阅读全文