我使用以下代码:
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))
您遇到的问题是函数在它看到的第一个返回行结束。你知道吗
所以。排队
它只返回第一个值:
pages[0]['title']
。你知道吗解决这个问题的一种方法是使用列表理解
另一种选择是使
recentchanges
成为生成器并使用yield
。你知道吗return
结束函数。所以循环只执行一次,因为您在循环中return
。想想看:一旦返回第一个值,调用者将如何获得后续值?他们需要再次调用函数吗?但那会重新开始。Python应该等到循环完成后立即返回所有值吗?但是他们会去哪里,Python怎么知道去做呢?你知道吗您可以通过
yield
而不是return
在这里提供生成器。您也可以返回一个发电机:无论哪种方式,调用方都可以根据需要将其转换为列表,或者直接对其进行迭代:
或者,您也可以返回标题列表:
一旦函数中达到了一个返回语句,该函数的执行就结束了,因此第二个返回就不会被执行。为了返回这两个值,需要将它们打包到列表或元组中:
它使用列表理解来列出所有您希望函数返回的对象,然后返回它。你知道吗
然后可以从返回列表中解包单个结果:
相关问题 更多 >
编程相关推荐