成功地向Python列表添加元素

0 投票
5 回答
1964 浏览
提问于 2025-04-15 15:34

这看起来可能是世界上最简单的Python问题……但我还是想试着解释一下。

基本上,我需要遍历从查询中得到的多个页面的json结果。

标准的结果是这样的:

{'result': [{result 1}, {result 2}], 'next_page': '2'}

我需要这个循环继续进行,把结果中的列表添加到一个变量里,这样我可以后续访问并计算列表中的结果数量。不过,我希望这个循环只在存在next_page的情况下进行,因为过一段时间后,如果没有更多页面,next_page这个键就会从字典中消失。

目前我有这样的代码:

next_page = True
while next_page == True:
    try:
        next_page_result = get_results['next_page'] # this gets the next page
        next_url = urllib2.urlopen("http://search.twitter.com/search.json" + next_page_result)# this opens the next page
        json_loop = simplejson.load(next_url) # this puts the results into json
        new_result = result.append(json_loop['results']) # this grabs the result and "should" put it into the list
    except KeyError:
        next_page = False   
        result_count = len(new_result)

5 个回答

1

你想要使用

result.append(json_loop['results']) # this grabs the result and "should" put it into the list
new_result = result

如果你坚持要这样做的话。正如Bastien所说,result.append(whatever) == None

2
new_result = result.append(json_loop['results'])

这个列表是在调用方法时被添加的,算是一种副作用。append() 这个方法实际上返回的是 None,所以现在 new_result 变成了指向 None 的一个引用。

4

另一种更简洁的方法,就是把所有内容放在一个大列表里:

results = []
res = { "next_page": "magic_token_to_get_first_page" }
while "next_page" in res:
    fp = urllib2.urlopen("http://search.twitter.com/search.json" + res["next_page"])
    res = simplejson.load(fp)
    fp.close()
    results.extend(res["results"])

撰写回答