我有一个包含几个句子的文件,并且我对命名实体使用了多语言,现在我希望所有句子(数字)应逐步传递给另一个函数。但是此函数仅返回句子编号之一,而不是全部。
def return_sentence_number():
for i in range(len(file.sentences)):
sentence_no = file.sentences[i]
return sentence_no
如果我打印文件,它看起来像:
print(file.sentences)
输出:
[Sentence("Ashraf Ghani president of Afghanistan"), Sentence("Bill Gates founder of Microsoft"), ....]
预期输出:
将第一个,然后第二个,...个句子的数量返回其他函数。
答案 0 :(得分:3)
从函数返回时,该函数将停止执行,因为 return 表示该函数已完成其工作,因此被终止了,有两种方法可以解决此问题。
def return_sentence_number():
sentences = []
for i in range(len(file.sentences)):
sentence_no = file.sentences[i]
sentences.append(sentence_no)
return sentences
sentences = return_sentence_number() # contains a list
# Iterate over values and do something
for sentence in sentences:
pass
1a。使用列表理解返回列表
def return_sentence_number():
return [sentence_no for sentence_no in file.sentences]
sentences = return_sentence_number() # contains a list
# Iterate over values and do something
for sentence in sentences:
pass
def return_sentence_number():
sentences = []
for i in range(len(file.sentences)):
sentence_no = file.sentences[i]
yield sentence_no
# Iterate over the generator and do something
for sentence in return_sentence_number():
pass
答案 1 :(得分:0)
您的return语句将在循环的第一次迭代中返回。
也许尝试使用yield