CODE1
import os
def walk_dir(dirname):
for d in os.listdir(dirname):
path = os.path.join(dirname, d)
if os.path.isdir(path):
for f in walk_dir(path):
print f
else:
yield path
for file in walk_dir("/tmp"):
print file
码2
import os
def walk_dir(dirname):
for d in os.listdir(dirname):
path = os.path.join(dirname, d)
if os.path.isdir(path):
for f in walk_dir(path):
yield f
else:
yield path
for file in walk_dir("/tmp"):
print file
当code1和code2运行时,它得到相同的输出,我想知道为什么?
为什么yield f
和print f
可以获得相同的效果?
import os
def walk_dir(dirname):
for d in os.listdir(dirname):
path = os.path.join(dirname, d)
if os.path.isdir(path):
for f in walk_dir(path):
pass
else:
yield path
for file in walk_dir("/tmp"):
print file
为什么code3无法得到正确答案?如果你添加:打印f for for for循环for f in walk_dir(path)
,print f
将无法运行,为什么我不能减去传球?
考虑函数中的问题,将code2修改为code4,
code4
import os
def walk_dir(dirname):
for d in os.listdir(dirname):
path = os.path.join(dirname, d)
if os.path.isdir(path):
walk_dir(path)
else:
print path
我把它改成一个简单的函数,当运行walk_dir(“/ tmp”)时,我得到了正确的输出。
让我们将code4修改为code5
代码4
import os
def walk_dir(dirname):
for d in os.listdir(dirname):
path = os.path.join(dirname, d)
if os.path.isdir(path):
walk_dir(path)
else:
yield path
for file in walk_dir("/tmp"):
print file
code5无法正常使用 我觉得我有些困惑,你能让我清楚吗?
答案 0 :(得分:3)
他们不做同样的事情。 yield
将值返回给调用者。 print
将内容写入sys.stdout
。
在这种情况下,当调用者从yield
获取一个值时,它只是打印它,所以最终结果是相同的......
答案 1 :(得分:2)
在后一个程序中,最后在循环中打印yield
的所有内容。尝试将最后一行更改为
print("Yielded: " + file)
看看我的意思。
答案 2 :(得分:0)
在两个代码中,您正在打印f。在第一个你在函数中打印f,在第二个代码中你在最后一个循环中打印f。
见评论......
代码1
import os
def walk_dir(dirname):
for d in os.listdir(dirname):
path = os.path.join(dirname, d)
if os.path.isdir(path):
for f in walk_dir(path):
print f # -----> You print f but don't runed it
else:
yield path
for file in walk_dir("/tmp"):
print file
代码2
import os
def walk_dir(dirname):
for d in os.listdir(dirname):
path = os.path.join(dirname, d)
if os.path.isdir(path):
for f in walk_dir(path):
yield f # --> You don't print f but return f to the loop
else:
yield path
for file in walk_dir("/tmp"):
print file