也许使用生成器是个不错的选择
import os
res = (path for path,_,_ in os.walk("path") if "bar" in path)
注意:我使用“/”作为根路径,因为我的系统类似于 unix。如果您在 Windows 上,将“/”替换为“C:\”(或任何您想要的)
优点:
- 生成器使用的内存少得多,并且在计算时不会“阻塞”系统。
示例:
# returns immediately
res = (path for path,_,_ in os.walk("/") if "bar" in path)
#I have to wait (who knows how much time)
res = [path for path,_,_ in os.walk("/") if "bar" in path]
- 您可以一次获得一条路径,而只需等待找到下一条“路径”所需的时间
示例:
res = (path for path,_,_ in os.walk("/") if "bar" in path)
# the for starts at no time
for path in res:
# at each loop I only wait the time needed to compute the next path
print(path) # see the path printed as it is computed
res = [path for path,_,_ in os.walk("/") if "bar" in path]
# the for starts only after all paths are computed
for path in res:
# no wait for each loop.
print(path) # all paths printed at once
- 如果您想保留“路径”找到的部分,您可以将其存储在列表中,并且只有您感兴趣的“路径”(内存使用量更少)
示例:
res = (path for path,_,_ in os.walk("/") if "bar" in path)
path_store = []
for path in res:
# I'm only interested in paths having odd length
# at the end of the loop I will use only needed memory
if(len(path)%2==1):
path_store.append(path)
- 如果您已经完成并且您对寻找更多“路径”不感兴趣,您可以随时停止,从而节省所有未计算路径所需的时间
示例:
res = (path for path,_,_ in os.walk("/") if "bar" in path)
path_store = []
count = 10
for path in res:
# I'm only interested in paths having odd length
if(len(path)%2==1):
count -= 1
path_store.append(path)
# I'm only interested in the first 10 paths.
# Using generator I waited only for the computation of those 10 paths.
# Using list you will always wait for the computation for all paths
if( count <= 0 ):
break
缺点:
在代码中 path 在每次迭代中都会丢失。
在循环结束时,res 已用尽,不再可用。
我必须将我感兴趣的路径存储在列表 path_store 中。
path_store = []
for path in res:
# I'm only interested in paths having odd length
if(len(path)%2==1):
path_store.append(path)
path = next(res) # Error StopIteration