如何将打印功能的结果添加到列表中[重复]
Posted
技术标签:
【中文标题】如何将打印功能的结果添加到列表中[重复]【英文标题】:How do I add the result of a print function ito a list [duplicate] 【发布时间】:2022-01-09 16:22:43 【问题描述】:我有以下定义以打印功能结尾的东西:
from nltk.corpus import words
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']):
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]]
result = print(sorted(temp, key = lambda val:val[0])[0][1])
return result
answer_nine()
我已正确打印出三个结果,但我希望将它们列在一个列表中。我尝试以多种不同的方式将它们分配到一个列表中,但我总是收到以下错误消息:AttributeError: 'NoneType' object has no attribute 'append'。 我不明白为什么我的结果有如果 NoneType 有值,我在这里缺少什么?
ps.:如果我像这样删除打印功能:result = sorted(temp, key = lambda val:val[0])[0][1]
我只收到第三个单词,但至少它有字符串作为类型。
【问题讨论】:
【参考方案1】:def answer_nine(entries=['cormulent', 'incendenece', 'validrate']):
result = []
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]]
result.append(sorted(temp, key = lambda val:val[0])[0][1])
return result
返回['corpulent', 'indecence', 'validate']
【讨论】:
非常感谢!我发誓我也试过这个,但不知何故它也对我有用!也许我之前的代码中有错字或其他东西:,)【参考方案2】: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_2=[]
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]]
result_2.append(sorted(temp, key = lambda val:val[0])[0][1])
result = print(sorted(temp, key = lambda val:val[0])[0][1])
return result, result_2
a,b=answer_nine()
print(a)
print(b)
此代码对我有用!并在列表中给出与函数调用相同的字符串,但 None 值除外
【讨论】:
以上是关于如何将打印功能的结果添加到列表中[重复]的主要内容,如果未能解决你的问题,请参考以下文章