返回多个resu

2024-09-30 22:15:53 发布

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

我使用以下代码:

def recentchanges(bot=False,rclimit=20):
    """
    @description: Gets the last 20 pages edited on the recent changes and who the user who     edited it
    """
    recent_changes_data = {
        'action':'query',
        'list':'recentchanges',
        'rcprop':'user|title',
        'rclimit':rclimit,
        'format':'json'
    }
    if bot is False:
        recent_changes_data['rcshow'] = '!bot'
    else:
        pass
    data = urllib.urlencode(recent_changes_data)
    response = opener.open('http://runescape.wikia.com/api.php',data)
    content = json.load(response)
    pages = tuple(content['query']['recentchanges'])
    for title in pages:
        return title['title']

当我做recentchanges()我只得到一个结果。如果我打印出来,所有的页面都会打印出来。
我只是误会了还是这和python有关?你知道吗

此外,开场白是:

cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

Tags: thefalsedatatitlebotpagesopenerquery
3条回答

您遇到的问题是函数在它看到的第一个返回行结束。你知道吗

所以。排队

for title in pages:
    return title['title']

它只返回第一个值:pages[0]['title']。你知道吗

解决这个问题的一种方法是使用列表理解

return [ title['title'] for title in pages ]

另一种选择是使recentchanges成为生成器并使用yield。你知道吗

for title in pages:
    yield title['title']

return结束函数。所以循环只执行一次,因为您在循环中return。想想看:一旦返回第一个值,调用者将如何获得后续值?他们需要再次调用函数吗?但那会重新开始。Python应该等到循环完成后立即返回所有值吗?但是他们会去哪里,Python怎么知道去做呢?你知道吗

您可以通过yield而不是return在这里提供生成器。您也可以返回一个发电机:

return (page['title'] for page in pages)

无论哪种方式,调用方都可以根据需要将其转换为列表,或者直接对其进行迭代:

titles = list(recentchanges())

# or

for title in recentchanges():
    print title

或者,您也可以返回标题列表:

return [page['title'] for page in pages]

一旦函数中达到了一个返回语句,该函数的执行就结束了,因此第二个返回就不会被执行。为了返回这两个值,需要将它们打包到列表或元组中:

...
returnList = [title['title'] for title in pages]
return returnList

它使用列表理解来列出所有您希望函数返回的对象,然后返回它。你知道吗

然后可以从返回列表中解包单个结果:

answerList = recentchanges()
for element in answerList:
    print element

相关问题 更多 >