the effect of yield an print in generator?
代码1
1 2 3 4 5 6 7 8 9 10 11 12 | 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
1 2 3 4 5 6 7 8 9 10 11 12 | 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运行时,它得到相同的输出,我想知道为什么?为什么
正如凡妮亚·米拉格罗斯·费尔南德斯所说:打印f----->你打印f,但不要运行它。我们再讨论一下。代码3
1 2 3 4 5 6 7 8 9 10 11 12 | 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-in表示loop
1 2 3 4 5 6 7 8 | 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")时,我得到了正确的输出。
让我们把代码4改成代码5代码5
1 2 3 4 5 6 7 8 9 10 11 | 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 |
"代码5"无法获得正确的电源。我觉得有什么东西把我搞糊涂了,你能告诉我吗?
他们不做同样的事。
然而,在这种情况下,当调用者从
在后一个程序中,您的
1 | print("Yielded:" + file) |
看看我的意思。
在这两个代码中,您都在打印f。第一个代码在函数中打印f,第二个代码在最后一个循环中打印f。
看到评论…
代码1
1 2 3 4 5 6 7 8 9 10 11 12 | 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
1 2 3 4 5 6 7 8 9 10 11 12 | 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 |