![](/img/trans.png)
[英]How do I return the value from each iteration of a loop to the function it is running within?
[英]How do i return each value in a loop?
我不想打印每個句子,而是想將其退回! 但是,如果我返回,它將結束循環。
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”,則該字符串應打印為“ Hearts 6”。 該函數應以列表形式返回文件的內容。
也許您想創建一個生成器:
def printDeck():
"""return contents of file as string"""
...
for sentence in contents: # for each line in contents
...
yield '{0} of {1}'.format(sentence[0],sentence[1])
然后將其用作
deck = printDeck()
deck1 = next(deck)
deck2 = next(deck)
etc.
要么
for deck in printDeck():
print(deck)
您只能在函數中返回一次值。 但是您可以將生成的字符串附加到mylst
,然后在循環完成后返回mylst
。
mylst = []
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
mylst.append('{0} of {1}'.format(sentence[0],sentence[1]))
return mylst
您無法返回一個句子並停留在循環中。 您可以返回已交換短語的列表,如下所示:
mylst = []
for sentence in contents: # for each line in contents
sentence = sentence.split() # eliminate spaces and turn into a list
phrase = sentence[1] + " of " + sentence[0]
mylst.append(phrase)
return mylst
寫printDeck()
作為產生琴弦發電機。 然后遍歷該生成器以進行打印。
您無需通過readlines()
一次性將整個文件讀入內存。 如果您在上下文管理器中打開文件( with
),則無需擔心關閉文件-上下文管理器將確保這種情況發生。
可以使用str.format()
逆轉句子的前2個單詞,而不必費心在拆分后實際交換順序。
您可以將代碼作為生成器編寫,並且更清晰地像這樣:
def read_deck(fileName):
with open(fileName) as f:
for sentence in f:
yield '{0[1]} of {0[0]}'.format(sentence.split())
>>> for s in read_deck('deck.txt'):
... print(s)
如果要將所有字符串都放在一個列表中,請在生成器上調用list()
:
>>> deck = list(read_deck('deck.txt'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.