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

时间:2016-02-11 00:36:42

标签: 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
        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()的函数,它接受一个参数,一个文件名。该函数应读入文件内容并以下面显示的格式打印。例如:if' Hearts 6'从文件中读入,字符串应打印为Hearts' 6。该函数应以列表形式返回文件的内容。

4 个答案:

答案 0 :(得分:4)

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

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)

答案 1 :(得分:1)

您只能在函数中返回一次值。但是您可以将生成的字符串附加到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

答案 2 :(得分:0)

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

<header id="header-wrap">
<div id="fixed">
<div class="row"><!--first row-->
    <div id="images">


        <a href="index.html">
          <img id="logo" src="images/logo2.png" alt="logo" 
           height="250" width="250">
        </a>



        <img id="text" src="images/header.png" alt="header"
         height="250" width="880">

    <div id="socialIcons">

        <div  class="social">
        <a href="#"><img src="images/twitter.png"></a>
        </div>

        <div class="social">
        <a href="#"><img src="images/facebook.png"></a>
        </div>

        <div class="social">
        <a href="#"><img src="images/youtube.png"></a>
        </div>

        <div class="social">
        <a href="#"><img src="images/instagram.png"></a>
        </div>
    </div>
    </div>
 </div>
</div>
</header>

答案 3 :(得分:0)

printDeck()写为产生字符串的生成器。然后遍历该生成器进行打印。

您无需使用readlines()一次性将整个文件读入内存。如果您在上下文管理器中打开文件(使用with),那么您不必担心关闭它 - 上下文管理器将确保发生这种情况。

可以使用str.format()撤消句子的前两个单词,而无需在拆分后实际交换订单。

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

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