You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python单词频率统计程序问题求助:输出不符合预期

问题描述

需求:编写程序读取单词列表,输出每个单词及其出现频率。

当前代码:

phase = input()
each_word = phase.split()

for x in each_word:
    word_count = each_word.count(x)

print(*each_word, word_count)

输入示例:

hey hi Mark hi mark

当前输出:

hey hi Mark hi mark 1

期望输出:

hey 1
hi 2
Mark 1
hi 2
mark 1
解决方案

你的思路是对的,用字典统计频率是更合理的方案——原代码里每次循环调用each_word.count(x)都会遍历整个列表,数据量大时效率很低,用字典可以做到一次遍历统计完所有频率。

修改后的代码实现:

phrase = input()
each_word = phrase.split()

# 第一步:统计每个单词的出现频率
word_freq = {}
for word in each_word:
    if word in word_freq:
        word_freq[word] += 1
    else:
        word_freq[word] = 1

# 第二步:遍历原单词列表,输出每个单词和对应的频率
for word in each_word:
    print(word, word_freq[word])

如果想简化统计逻辑,可以用Python标准库的collections.defaultdict:

from collections import defaultdict

phrase = input()
each_word = phrase.split()

word_freq = defaultdict(int)
for word in each_word:
    word_freq[word] += 1

for word in each_word:
    print(word, word_freq[word])

运行上述代码后,输入hey hi Mark hi mark就能得到你期望的输出。

内容的提问来源于stack exchange,提问作者Alexander Cortez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 11:59:56