首页 > 解决方案 > 以 24 个为一组,浏览范围内的所有文件

问题描述

我有以下循环

for file in range(10000):
    ...

这将遍历此范围内的所有文件并执行某些操作。

相反,我希望它仍然遍历所有“文件”,但以 24 个为一组。换句话说,应该考虑前 24 个“文件”进行特定计算(将该值存储在列表中),然后接下来的 24 个文件,依此类推,直到考虑 10000 个“文件”。

数字 10000 只是为了这个问题。

标签: pythonloopsfor-looprange

解决方案


使用 % 模运算符的一种方法:

processing = 0

for file in range(1000):
    if file % 24 == 0:
        processing += 1
    #Process your stuff, use processing var to store it
    #Like list_of_result[processing] or a dict_of_results[str(processing)] etc

它在这里说,每次文件的其余部分除以 24 等于 0,然后您更改您的处理集计数器变量值。

因此,对于前 24 个,处理将等于 1,对于接下来的 24 个,处理将等于 2,依此类推...

使用相同的 % 运算符但不是计数器的另一种方法:

results = []

for file in range(1000):
    if file % 24 == 0:
        if file != 0:
            #Store your slice of results in the main results list
            results.append(tmp_results.copy())
        #Clear the 24 batch result list
        tmp_results = [] #Or a dict

    #Process your stuff, store in in tmp_results

推荐阅读