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

调用词频统计函数后访问字典值遇'NoneType'下标错误的解决方法

解决'NoneType' object is not subscriptable错误

你的代码报错的核心原因是count_words函数没有返回值——Python中函数如果没有显式写return语句,默认会返回None。所以执行cnt = count_words(my_words)后,cnt是None,你尝试用cnt['just']访问下标自然会触发错误。

修改方法

在count_words函数末尾添加return cnt_dict,把统计好的字典返回出来:

def count_words(word_list):
    
    "Count word frequencies of words in a list."
    
    cnt_dict = dict()
    
    for word in word_list:
        if word in cnt_dict:
            cnt_dict[word] += 1
        else:
            cnt_dict[word] = 1
    print(cnt_dict)
    return cnt_dict  # 添加返回语句
  
my_words = ['this', 'is', 'just',
            'a', 'test', 'example', 'to',
           'test', 'some', 'example', 'code']
cnt = count_words(my_words)
print(cnt['just'])  # 现在可以正常获取值,输出1

额外优化(可选)

如果不想自己写循环统计词频,可以用Python标准库collections.Counter来简化代码,效果完全一致:

from collections import Counter

my_words = ['this', 'is', 'just',
            'a', 'test', 'example', 'to',
           'test', 'some', 'example', 'code']
cnt = Counter(my_words)
print(cnt['just'])  # 输出1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:50:36