python - python中嵌套循环操作的替代方案?
问题描述
我想要一个嵌套循环操作的快速替代方案,其中第二个循环发生在第一个循环中的某些操作之后。
例如:
date = target_date_list = pd.date_range(start=start_date, end=end_date).strftime(f'year=%Y/month=%m/day=%d')
for date in target_date_list:
folder = f'path_to_folder/{date}'
for file in folder:
//some operation
解决方案
这里没有有意义的更快的选择。内循环的值依赖于外循环产生的值,所以使用的微优化itertools.product
是不可用的。
如果您实际上是在迭代一个目录(不是描述目录的字符串中的字符),我强烈建议您使用os.scandir
over os.listdir
(假设像许多人一样,您使用后者而不知道前者的存在),因为它在以下情况下要快得多:
- 您正在对大型目录进行操作
- 您正在根据统计信息过滤内容(特别是条目类型,它们完全免费提供而没有统计信息)
使用os.scandir
, 和内部循环之前实现如下:
for file in os.listdir(dir):
path = os.path.join(dir, file)
if file.endswith('.txt') and os.path.isfile(path) and os.path.getsize(path) > 4096:
# do stuff with 4+KB file described by "path"
可以通过更改为稍微简化并加快速度:
with os.scandir(dir) as direntries:
for entry in direntries:
if entry.name.endswith('.txt') and entry.is_file() and entry.stat().st_size >= 4096:
# do stuff with 4+KB file described by "entry.path"
但从根本上说,这种优化与避免嵌套循环无关;如果要迭代所有文件,则必须迭代所有文件。即使您将其隐藏在实用程序方法后面,嵌套循环也需要以某种方式发生,并且相对于文件系统访问的成本而言,成本将没有意义。
推荐阅读
- javascript - 避免在我自己的网站内进行会话劫持
- neo4j - Neo4j 从 csv 导入零记录
- c# - vs 和 vs 代码在程序目录中的区别
- amazon-web-services - AWS IoT,如何从我的 API 端点获取 UUID
- mysql - FULL TEXT 仅在至少 X 个单词匹配时选择
- html - 通过 VBA 从 HTML 中抓取具有重复跨度 id 的特定跨度 id
- css - 使用样式化组件创建变体的方法
- azure-container-instances - Azure 容器实例上的 Net Core 3.1 gRPC 服务器仅侦听端口 80
- python - 在 PyCharm 中使用预提交
- javascript - 部署到 Firebase 的问题