2016-06-08 67 views
-1

背景返回數字

我一些REST JSON工作的批次Python-最有效的方法通過Python調用獲得用戶的列表。不幸的是,服務器一次只能返回最多50個用戶。 例如

呼叫「[0:49]」返回第50個用戶

呼叫「[51:99]」返回下一批次50個用戶

服務器的因此不會返回用戶的總數,我可以編寫一些邏輯來讓所有用戶有多個休息電話。

問題

我寫了打印在字典格式的數據非常凌亂功能:

def get_all_possible_items(max_no_users): 
     dict={} 
     base=0 
     values=max_no_users//50 
     if max_no_users>49: 
      dict[base]=base+49 
      base+=49 
     else: 
      base-=1 
     for i in range(values-1): 
      base+=1 
      dict[base]=base+49 
      base+=49 
     dict[base+1]=max_no_users 

     print dict 

    get_all_possible_items(350) 

輸出看起來像:

如果max_no_users是350:

{0:49,100:149,200:249,300:349,50 :99,150:199,250:299,350:350}

如果max_no_users是351:

{0:49,100:149,200:249,300:349,50 :99,150:199,250:299,350:351}

有沒有更好的寫作方法(必須有!)?

+0

什麼是f由REST調用返回的數據的orm?我想'dict.update(json.loads(REST_data))' – nigel222

回答

1

您可以簡單地使用python的range(start, stop, step)。您可以設置step爲50即

>>> for i in range(0, max_no+1, 50): 
...  print i, i+49 
... 
0 49 
50 99 
100 149 
150 199 
200 249 
250 299 
300 349 
350 399 

然後可能有一個額外的if語句的最後一個號碼,以確保它不會超過最大數量,即。

>>> for i in range(0, max_no+1, 50): 
...  print i, i+49 if i+49 < max_no else max_no 
... 
0 49 
50 99 
100 149 
150 199 
200 249 
250 299 
300 349 
350 350 

編輯:要重點解決如何利用這一點,做這樣的事情:

def get_all_possible_items(max_no_users): 
    range_dict = {} 
    for i in range(0,max_no_users+1, 50): 
     if i+49 < max_no_users: 
      range_dict[i] = i+49 
     else: 
      range_dict[i] = max_no_users 
    return range_dict 

,或者如果你想這一切在同一行:

def get_all_possible_items(max_no_users): 
    return {i:i+49 if i+49 < max_no_users else max_no_users for i in range(0, max_no_users, 50)} 
+1

我正在寫這個想法,但它首先出現。我只會補充說,你可以在循環外聲明一個空字典,並在循環中用key = 1填充它,並且value = i + 49 part –

+0

我想,只要我給出了獲取數字的過程,他可以找出其餘的,但是,這是正確的。我將編輯。 –

+0

謝謝,這是一個完美的答案!我知道有一個更好的方法 – Thomas

0

試試這個: :您的結果不正確...在您的問題中

def get_all_possible_items(users): 
     return dict([[x, min(x+49,users) ] for x in range(0,users,50)]) 

    # or 
    #def get_all_possible_items(users): 
    #  print dict([[x, min(x+49,users) ] for x in range(0,users,50)]) 


    get_all_possible_items(350) 
     #{0: 49, 50: 99, 100: 149, 150: 199, 200: 249, 250: 299, 300: 349} 
    get_all_possible_items(351) 
     #{0: 49, 50: 99, 100: 149, 150: 199, 200: 249, 250: 299, 300: 349, 350: 351}