如何从for循环返回每个值

2024-10-04 03:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文

(使用python3.3.2)嗨,我正在尝试为文本云创建一个爬行函数,它将进入一个链接列表,理想情况下会返回该列表中每个元素的函数输出列表。但是,我一直在使用print函数print(b),而不是实际返回我想要的东西。在for循环中,如何返回从print(b)语句中获得的所有内容。它可以在一个列表中,也可以以某种方式编译。谢谢:) 我太长了,读不下去了。

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

Tags: of函数in文本url列表for链接
3条回答

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

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

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

第一种方法:

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

第二种方法:

^{pr2}$

可能最重要的区别是:如果对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只会失败(zeromdivisionerror:division by zero),并且不会打印任何内容。调用testG打印

-0.6666666666666666
-1.0
-2.0

然后失败(ZeroDivisionError:被零除)。在


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

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

相关问题 更多 >