Python 如何一次遍历列表 100 个元素,直到到达所有元素?

标签 python python-3.x python-3.6

给定一个函数 process_list,它获取一个唯一 ID 列表并将该列表发送到 API 端点进行处理。列表的限制是一次 100 个元素。

如果我有一个超过 100 个元素的列表,我该如何处理前 100 个,然后是下 100 个,直到达到 n?

my_list = [232, 231, 932, 233, ... n]
# first 100
process_list(my_list[:100])


def process_list(my_list):
    url = 'https://api.example.com'
    data = {'update_list': my_list}
    headers = {'auth': auth}
    r = requests.put(url, data=json.dumps(data), headers=headers)

最佳答案

尽量保持简单,因为我假设您是从 Python 开始

迭代列表,每次迭代增加一百

# builds a list of numbers from 0 thru 10122
my_list = [i for i in range(10123)]

# i will step through the indexes (not the items!) in the list
# 100 at a time,
for i in range(0, len(my_list), 100):
    # call our helper to process a sub list
    process_list(my_list[i:i+100])

# helper to process a sub list
def process_list(my_list):       
    url = 'https://api.example.com'
    data = {'update_list': my_list}
    headers = {'auth': auth}
    r = requests.put(url, data=json.dumps(data), headers=headers)

关于如何使用 docs 中的 range,您有两个选择:

range(start, stop[, step])

range(stop)

使用第一个选项迭代序列 0, 100, 200, ...

关于Python 如何一次遍历列表 100 个元素,直到到达所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56518479/

相关文章:

python - Anaconda Python 3.6——pythonw 和 python 应该是等价的吗?

python - 按特定键的降序对字典列表进行排序

列表的 Python 问题(TypeError : 'NoneType' object is not iterable)

python - 使用列表理解进行元组解包失败,但可以使用 for 循环

python - 如何在 Python 中强制静态类型化?

python - 语法错误 : name 'cows' is assigned to before global declaration in Python3. 6

python - 仅使用列表理解重新排列(列表列表)矩阵

python - 从索引对创建倍数的元组

python - 如何处理生成签名 URL 以通过 CloudFront 访问私有(private)内容的性能?

Python/Google Drive API - orderBy 'name' 和 orderBy 'name_natural' 之间有什么区别?