【发布时间】:2016-05-21 14:32:00
【问题描述】:
我不想打印每个句子,而是要返回它! 但如果我返回,它将结束循环。
def printDeck(fileName):
infile = open(fileName,'r') # open file
contents = infile.readlines() # read file
infile.close() # close file
for sentence in contents: # for each line in contents
sentence = sentence.split() # eliminate spaces and turn into a list
sentence[0], sentence[1] = sentence[1], sentence[0] # reverse order
print('{0} of {1}'.format(sentence[0],sentence[1]))
这是我试图解决的练习:
编写一个名为 printDeck() 的函数,它接受一个参数,一个文件名。该函数应读入文件的内容并以如下所示的格式打印。例如:如果从文件中读入“Hearts 6”,则字符串应打印为“6 of Hearts”。该函数应该以列表形式返回文件的内容。
【问题讨论】:
-
您不能多次返回。您可以根据需要返回一个列表或元组,但是当您返回时,控制流会跳回调用者。
-
您在寻找
yield吗? -
或许
printDeck应该重命名为getDeck?
标签: python loops python-3.x for-loop return