使用python语言编写小程序要求是:用户输入若干英文单词中间用空格分隔。每个单词及其出现次数作为字典的键值对并输出该字典
代码如下:
words = input("请输入若干英文单词,中间用空格分隔:")
word_list = words.split() # 将输入的字符串按空格分割成单词列表
word_dict = {} # 创建空字典
# 统计每个单词出现的次数
for word in word_list:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
# 输出字典
print(word_dict)
使用示例:
请输入若干英文单词,中间用空格分隔:apple banana orange apple pear apple
{'apple': 3, 'banana': 1, 'orange': 1, 'pear': 1}
原文地址: https://www.cveoy.top/t/topic/bDZk 著作权归作者所有。请勿转载和采集!