python - 以 24 个为一组,浏览范围内的所有文件
问题描述
我有以下循环
for file in range(10000):
...
这将遍历此范围内的所有文件并执行某些操作。
相反,我希望它仍然遍历所有“文件”,但以 24 个为一组。换句话说,应该考虑前 24 个“文件”进行特定计算(将该值存储在列表中),然后接下来的 24 个文件,依此类推,直到考虑 10000 个“文件”。
数字 10000 只是为了这个问题。
解决方案
使用 % 模运算符的一种方法:
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
推荐阅读
- http - HTTP 调用的日志框架
- elasticsearch - Elasticsearch 不在 query_string 查询中使用同义词分析器
- f# - 如何在 F# 类型中创建与 C# 类中的委托等效的委托?
- javascript - google firebase 是如何保存用户数据的,以便用户每次登录时,他们之前在网站上所做的工作仍然存在?
- python - 将循环数据保存到数据框中的新列
- database - 如何计算扫描的索引页面和扫描的关系页面
- javascript - 如果单击外部,则 JQuery 显示/隐藏和折叠
- html - jQuery CSS 框架的正确样式
- flutter - 验证时 globalkey formstate 返回 false
- facebook-graph-api - 有人用stackpost发脸书吗?