# 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_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
也许用发电机是个不错的选择
注意:我使用“/”作为根路径,因为我的系统类似于unix。如果您使用的是windows,请将“/”替换为“C:\”(或任何您想要的内容)
优点:
示例:
示例:
示例:
示例:
缺点:
不能对生成器使用索引。你只能得到下一个项目。
如果您想要一个同时包含所有路径的列表,则必须将其转换为一个列表(因此最好使用列表理解)
生成器只向前一步(获取下一个元素后不能返回)
如果要保留某些“路径”,必须将其存储在某个位置(如列表),否则它将丢失
在代码中,每次迭代都会丢失路径。 循环结束时,res已耗尽,不再可用。 我必须将我感兴趣的路径存储在列表路径存储中。你知道吗
试试这个:
相关问题 更多 >
编程相关推荐