Python 如何在循环中返回每个值?

Python 如何在循环中返回每个值?,python,loops,python-3.x,for-loop,return,Python,Loops,Python 3.x,For Loop,Return,我不想打印每个句子,而是想把它还给你! 但如果我返回,它将结束循环 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

我不想打印每个句子,而是想把它还给你! 但如果我返回,它将结束循环

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”。函数应该以列表形式返回文件的内容。

您不能返回一句话而停留在循环中。您可以返回交换短语的列表,如下所示:

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
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)

你不能只返回一句话就停留在循环中。您可以返回交换短语的列表,如下所示:

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
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)

也许您想创建一个生成器:

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 = list(read_deck('deck.txt'))
然后用它作为

deck = printDeck()
deck1 = next(deck)
deck2 = next(deck)
etc.


也许您想创建一个生成器:

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 = list(read_deck('deck.txt'))
然后用它作为

deck = printDeck()
deck1 = next(deck)
deck2 = next(deck)
etc.


函数中的值只能返回一次。但您可以将生成的字符串附加到
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
,然后在循环完成后返回
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
编写
printDeck()
,作为生成字符串的生成器。然后迭代该生成器进行打印

您不需要使用
readlines()
一次性将整个文件读入内存。如果在上下文管理器中打开该文件(使用
),则无需担心关闭它-上下文管理器将确保这一点

使用
str.format()
可以反转句子的前两个单词,而无需在拆分后实际交换顺序

您可以将代码编写为生成器,更清楚地如下所示:

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
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()

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 = list(read_deck('deck.txt'))
编写
printDeck()
,作为生成字符串的生成器。然后迭代该生成器进行打印

您不需要使用
readlines()
一次性将整个文件读入内存。如果在上下文管理器中打开该文件(使用
),则无需担心关闭它-上下文管理器将确保这一点

使用
str.format()
可以反转句子的前两个单词,而无需在拆分后实际交换顺序

您可以将代码编写为生成器,更清楚地如下所示:

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
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()

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 = list(read_deck('deck.txt'))


您不能多次返回。如果需要,可以返回列表或元组,但返回时控制流跳回调用者。是否正在查找
yield
?可能
printDeck
应重命名为
getDeck
?不能多次返回。如果需要,可以返回列表或元组,但返回时控制流会跳回调用方。是否正在查找
yield
?也许
printDeck
应该重命名为
getDeck
?每次调用它时,它都会返回下一个值。事实并非如此。他们需要调用它一次以获取生成器对象,然后对其进行迭代(或者对其使用
next()
)。抱歉,很久没有这样做了)下一步(deck)是python3问题被标记为python3,除此之外,它在python2中仍然有效。每次调用它时,它都返回下一个值。事实并非如此。他们需要调用它一次以获取生成器对象,然后对其进行迭代(或者对其使用
next()
)。很抱歉,很久没做了)下一步(甲板)是Python3问题被标记为Python3,除此之外,它在Python2中仍然可以工作。非常感谢,这正是我所需要的!非常感谢,这正是我需要的!一般来说,发电机是解决此问题的最佳方案。这个答案将整个文件读入内存,然后返回一个大列表中的所有内容。你仍然需要遍历列表才能打印,所以在解决这类问题时,你最好利用生成器的效率。在我写答案时,我们甚至不知道涉及到一个文件。但感谢您的澄清评论。它始终涉及一个文件,但这回答了OPs的问题,因为它返回所需的列表对象(也可以通过调用生成器对象上的
list()
使用生成器来完成)。我没有立即看到它。无论如何,OP接受了这个答案,这是一个可行的解决方案(至少对于小文件而言)。事实上,这似乎是一个纸牌游戏,因此数据量不应该太大。让我们建议@丹如果他遇到内存问题,可以考虑迭代器/生成器。特别是,
infle
已经是其中之一,因此对于文件来说,它确实是有意义的。一般来说,生成器是解决此问题的最佳方案。这个答案将整个文件读入内存,然后返回一个大列表中的所有内容。你仍然需要遍历列表才能打印,所以在解决这类问题时,你最好利用生成器的效率。在我写答案时,我们甚至不知道涉及到一个文件。但感谢您的澄清评论。它始终涉及一个文件,但这回答了OPs的问题,因为它返回所需的列表对象(也可以通过调用生成器对象上的
list()
使用生成器来完成)。我没有立即看到它。无论如何,OP接受了这个答案,这是一个可行的解决方案(至少对于小文件而言)。事实上,这似乎是一个纸牌游戏,因此数据量不应该太大。让我们建议@丹如果他遇到内存问题,可以考虑迭代器/生成器。特别是,
infle
已处于启用状态