让我理解什么时候yield和recursion同时发生是很复杂的。我想用我的代码遍历文件目录:
import os
def doc_iter(fpath):
if os.path.isdir(fpath):
for child in os.listdir(fpath):
child=os.path.join(fpath,child)
print "this is ",child
for cn in doc_iter(child):
print "i am here1"
yield cn
print "yiedl1",cn
else:
print "i am here2"
yield fpath
print "yield2",fpath
有一个
目录,里面有test
三个子目录目录test1,test2,test3
里面有两个文件
目录里面有两个文件
目录里面有两个文件test1
test11,test12
test2
test21,test22
test3
test31,test32
>>> a.next()
this is /home/debian/test/test2
this is /home/debian/test/test2/test22
i am here2
i am here1
i am here1
'/home/debian/test/test2/test22'
>>> a.next()
yiedl1 /home/debian/test/test2/test22
yiedl1 /home/debian/test/test2/test22
yield2 /home/debian/test/test2/test22
this is /home/debian/test/test2/test21
i am here2
i am here1
i am here1
'/home/debian/test/test2/test21'
>>> a.next()
yiedl1 /home/debian/test/test2/test21
yiedl1 /home/debian/test/test2/test21
yield2 /home/debian/test/test2/test21
this is /home/debian/test/test3
this is /home/debian/test/test3/test32
i am here2
i am here1
i am here1
'/home/debian/test/test3/test32'
>>> a.next()
yiedl1 /home/debian/test/test3/test32
yiedl1 /home/debian/test/test3/test32
yield2 /home/debian/test/test3/test32
this is /home/debian/test/test3/test31
i am here2
i am here1
i am here1
'/home/debian/test/test3/test31'
>>> a.next()
yiedl1 /home/debian/test/test3/test31
yiedl1 /home/debian/test/test3/test31
yield2 /home/debian/test/test3/test31
this is /home/debian/test/test1
this is /home/debian/test/test1/test11
i am here2
i am here1
i am here1
'/home/debian/test/test1/test11'
>>> a.next()
yiedl1 /home/debian/test/test1/test11
yiedl1 /home/debian/test/test1/test11
yield2 /home/debian/test/test1/test11
this is /home/debian/test/test1/test12
i am here2
i am here1
i am here1
'/home/debian/test/test1/test12'
>>> a.next()
yiedl1 /home/debian/test/test1/test12
yiedl1 /home/debian/test/test1/test12
yield2 /home/debian/test/test1/test12
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
输出让我很恼火,
1.产量1中的打印等于产量2?
2.至少有两个yield语句要运行,教科书上说when run into yield ,the program will be halt, the next next() make it continue
??3.我们分析一下第一个next()的输出,为什么yield cn`后面有两个 i am here1
s ?
5.如何详细绘制计算树?6.如果你写一个函数来遍历目录,i am here2"
4.what is the function of
bottom=[]
import os
def doc_iter(fpath):
if os.path.isdir(fpath):
for child in os.listdir(fpath):
child=os.path.join(fpath,child)
doc_iter(child)
else:
bottom.append(fpath)
return bottom
输出是:
doc_iter("/home/debian/test")
['/home/debian/test/test2/test22', '/home/debian/test/test2/test21', '/home/debian/test/test', '/home/debian/test/test3/test32' , '/home/debian/test/test3/test31', '/home/debian/test/test~', '/home/debian/test/test1/test11', '/home/debian/test/test1/test12 ']
函数和迭代器有区别,在函数中:
doc_iter(child)
在迭代器中:
for cn in doc_iter(child):
yield
在这个例子中它是多么复杂!