如何从for循环返回每个值

时间:2013-12-11 21:19:29

标签: python loops for-loop return python-3.3

(使用python 3.3.2)嗨,我正在尝试为文本云创建一个爬行函数,它将进入一个链接列表,理想情况下返回该列表中每个元素的函数输出列表。但是,我坚持使用打印功能,打印(b),而不是实际返回我想要的。在我的for循环中,我如何从print(b)语句中返回所有内容。它可以都在一个列表中或以某种方式编译。谢谢 :) tl; dr:我如何返回从for循环获得的所有内容

def crawl():
    linkList = inputFunction()[1:][0] #makes a list of a bunch of URL's
    for i in range(len(linkList)):
        print(i)
        t = getHTML(linkList[i]) #getHTML returns tuple of text in the input URL
        alreadyCrawl = alreadyCrawl + list(linkList[i]) #ignore this
        t = list(t)
        b = counting(t) #makes dictionary of word counts
        print(b) 
    return

3 个答案:

答案 0 :(得分:8)

要么将它们放在列表中并在结尾处返回列表,要么"yield"它们(因此创建一个生成器)。

第一种方式:

def f():
    acc = []
    for x in range(10):
        acc.append(someFunctionOfX(x))
    return acc

第二种方式:

def g():
    for x in range(10):
       yield someFunctionOfX(x)

可能最重要的区别如下:如果对someFunctionOfX的任何调用导致示例1中的异常,则该函数将不返回任何内容。在示例2中,如果假设由于某种原因无法产生第5个值,则前四个值已经产生并且可能在调用者的上下文中使用。

在这里你可以看到差异:

def f():
    acc = []
    for x in range(-3, 4):
        acc.append (2 / x)
    return acc

def g():
    for x in range(-3, 4):
        yield 2 / x

def testF():
    for x in f(): print(x)

def testG():
    for x in g(): print(x)

调用testF失败(ZeroDivisionError:除以零)并且不打印任何内容。调用testG打印

-0.6666666666666666
-1.0
-2.0

然后失败(ZeroDivisionError:除以零)。


返回列表或产生值的我(非常个人)标准如下:如果我需要存储某个地方的数据,我会返回一个列表。如果我只需要处理每个成员,我就会产生它们。

答案 1 :(得分:0)

您可以返回所需的值列表。

def crawl():
    list_ret = []   #create empty list to store values

    for i in range(len(linkList)):
        # do some stuff
        b = counting(t) #makes dictionary of word counts
        list_ret.append(b)  #append value to list
        print(b) 
    return list_ret   #return list of values

答案 2 :(得分:0)

def crawl():
    linkList = inputFunction()[1:][0] #makes a list of a bunch of URL's
    return_list = []
    for i in range(len(linkList)):
        print(i)
        t = getHTML(linkList[i]) #getHTML returns tuple of text in the input URL
        alreadyCrawl = alreadyCrawl + list(linkList[i]) #ignore this
        t = list(t)
        b = counting(t) #makes dictionary of word counts
        return_list.append(b) 
    return return_list
相关问题