Python返回数字批的最有效方法

2024-10-01 11:34:34 发布

您现在位置:Python中文网/ 问答频道 /正文

背景

我正在通过python处理一些restjson调用,以获取用户列表。不幸的是,服务器一次最多只能返回50个用户。 e、 g

call“[0:49]”返回前50个用户

call“[51:99]”返回下一批50个用户

服务器确实返回了用户总数,因此,我可以编写一些逻辑来获取具有多个rest调用的所有用户。你知道吗

问题

我编写了一个非常混乱的函数,它以字典格式打印数据:

    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)

输出如下所示:

如果最大无用户数为350:

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

如果max\u no\u users是351:

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

有没有更好的写作方法(一定有!)?你知道吗


Tags: no用户服务器basegetitemsallcall
2条回答

您只需使用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)}

试试这个::你的结果不正确。。。在你的问题上

    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}

相关问题 更多 >