質問

これは、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)
役に立ちましたか?

解決

代替一つの大きなリストを作る(クリーナー)アプローチ、:

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

他のヒント

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

リストは、メソッド呼び出しの副作用として添付されています。 append()が実際Noneを返し、そうnew_resultは現在Noneへの参照である。

あなたが使用したい。

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

あなたがそのように行う上で主張すれば。バスティアンが言ったように、result.append(whatever) == None

AFAICS、あなたは、すべての変数new_resultは必要ありません。

result_count = len(result)

あなたが必要な答えを与えるだろう。

あなたのdictの中にあなたのリストに追加することができdict..youに追加することはできません、あなたはこのように行う必要があります。

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

あなたはあなたの結果の辞書には、次のページの値がないかどうかを確認したい、とあなただけの行う

このように、辞書からキーを削除する場合
if not result['next_page']:
    del result['next_page']
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top