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

如何将print函数输出结果存入列表,解决返回NoneType报错问题

错误根因说明
  1. print() 函数的返回值固定为None,你看到控制台打印的内容是该函数输出到标准输出的内容,不属于函数返回值。你将print()的执行结果赋值给result变量,自然result的类型为NoneType,调用append方法就会触发属性不存在的报错。
  2. 去掉print()后仅返回第三个单词,是因为你在循环中每次都给result重新赋值,前两次的计算结果会被后续覆盖,循环结束后result仅保留最后一次迭代的结果。
修正后代码

要将所有结果存入列表,只需在函数初始化阶段创建空列表,每次迭代把计算出的修正单词追加到列表中,最终返回整个列表即可:

from nltk.corpus import words
import nltk
nltk.download('words')
correct_spellings = words.words()
from nltk.metrics.distance import jaccard_distance
from nltk.util import ngrams
from nltk.metrics.distance  import edit_distance    
        
def answer_nine(entries=['cormulent', 'incendenece', 'validrate']):
    # 初始化空列表存储所有修正结果
    result_list = []
    for entry in entries:
        temp = [(jaccard_distance(set(ngrams(entry, 2)), set(ngrams(w, 2))),w) for w in correct_spellings if w[0]==entry[0]]
        correct_word = sorted(temp, key = lambda val:val[0])[0][1]
        # 将当前修正结果追加到列表
        result_list.append(correct_word)
        # 若需要控制台同时打印,单独加这行即可
        print(correct_word)
    # 返回存储了所有结果的列表
    return result_list

# 调用函数即可拿到包含三个结果的列表
final_result = answer_nine()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:06:00