首页 > 解决方案 > 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

标签: python

解决方案


这里没有有意义的更快的选择。内循环的值依赖于外循环产生的值,所以使用的微优化itertools.product是不可用的。

如果您实际上是在迭代一个目录(不是描述目录的字符串中的字符),我强烈建议您使用os.scandirover os.listdir(假设像许多人一样,您使用后者而不知道前者的存在),因为它在以下情况下要快得多:

  1. 您正在对大型目录进行操作
  2. 您正在根据统计信息过滤内容(特别是条目类型,它们完全免费提供而没有统计信息)

使用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"

但从根本上说,这种优化与避免嵌套循环无关;如果要迭代所有文件,则必须迭代所有文件。即使您将其隐藏在实用程序方法后面,嵌套循环也需要以某种方式发生,并且相对于文件系统访问的成本而言,成本将没有意义。


推荐阅读