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

如何使用字典推导式统计列表中各长度单词的出现次数

问题原因

原写法存在两个核心问题:

  • 遍历每个单词时调用k.count(k),本质是统计单个单词k自身的出现次数,结果永远为1
  • 字典键具有唯一性,相同长度的单词生成的同键键值对会被后生成的覆盖,最终所有值都保持为1

修正方案

以下是三种可行的实现方式:

方案1:使用defaultdict计数

from collections import defaultdict

def words_lengths_map(text):
    # 这里如果需要处理传入的text参数,替换为对应分词得到的单词列表即可
    mod_text = ["hello", "this", "is", "a", "list", "of", "words"]
    count_dict = defaultdict(int)
    for word in mod_text:
        count_dict[len(word)] += 1
    print(dict(count_dict))

方案2:使用Counter极简实现

from collections import Counter

def words_lengths_map(text):
    mod_text = ["hello", "this", "is", "a", "list", "of", "words"]
    count_dict = Counter(len(word) for word in mod_text)
    print(dict(count_dict))

方案3:字典推导式实现

如果你一定要用字典推导式完成,可以先提取所有单词的长度列表,再对长度去重后统计次数:

def words_lengths_map(text):
    mod_text = ["hello", "this", "is", "a", "list", "of", "words"]
    len_list = [len(word) for word in mod_text]
    count_dict = {length: len_list.count(length) for length in set(len_list)}
    print(count_dict)

以上三种方案运行后都可以得到预期输出:

{5: 2, 4: 2, 2: 2, 1: 1}

内容的提问来源于stack exchange,提问作者Cecil Shepherd

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:54:01