【问题标题】:appending successfully to a python list成功附加到 python 列表
【发布时间】:2010-12-11 23:31:49
【问题描述】:

这似乎是世界上最简单的 python 问题......但我将尝试解释一下。

基本上我必须遍历查询的 json 结果页面。

标准结果是这样的

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

我需要循环继续循环,将结果键中的列表附加到一个 var 中,以后可以访问并计算列表中的结果数量。但是,我要求它仅在 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)

【问题讨论】:

  • 它说 next_page == False 它可能应该说 next_page = False。您正在分配,而不是检查是否相等。
  • 很好发现......我现在已经编辑了......感谢您指出这一点
  • foo == True 拼写为foo

标签: python list append dictionary


【解决方案1】:

另一种(更简洁的)方法,列出一个大清单:

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"])

【讨论】:

    【解决方案2】:
    new_result = result.append(json_loop['results'])
    

    列表作为方法调用的副作用附加。 append() 实际上返回 None,所以 new_result 现在是对 None 的引用。

    【讨论】:

    • @Neil Hickman:你不能“解决它。result.append 更新结果。它具有新的价值。如果你认为它有帮助,你可以说new_result=result,但result 是由append 更新。没有返回值:没有创建了一个新列表。
    【解决方案3】:

    你想用

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

    如果你坚持这样做。正如巴斯蒂安所说,result.append(whatever) == None

    【讨论】:

      【解决方案4】:

      AFAICS,您根本不需要变量 new_result。

      result_count = len(result)
      

      会给你你需要的答案。

      【讨论】:

        【解决方案5】:

        你不能追加到字典中。你可以追加到字典中的列表中,你应该这样做

        result['result'].append(json_loop['results'])
        

        如果你想检查结果字典中是否没有下一页值,并且你想从字典中删除键,就这样做

        if not result['next_page']:
            del result['next_page']
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-13
          • 2021-12-03
          • 2021-07-12
          • 2015-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-19
          相关资源
          最近更新 更多