Python - 在 for 循环中打印和 return
Python - print and return in for loops
我刚开始学习 Python。我从 here 看到了一段有趣的代码,作者用来解释短路。代码如下:
>>> def fun(i):
... print "executed"
... return i
...
我试着调用 fun(1)。输出如下,对我来说很有意义。
>>> fun(1)
executed
1
然后我尝试了 [fun(i) for i in [0, 1, 2, 3]]
,输出如下所示:
>>> [fun(i) for i in [0, 1, 2, 3]]
executed
executed
executed
executed
[0, 1, 2, 3]
我期待这样的事情:
executed
0
executed
1
executed
2
executed
3
谁能告诉我我做错了什么?谢谢!
试试
l = [fun(i) for i in [0, 1, 2, 3]]
这将输出
executed
executed
executed
executed
然后就执行l
,这样会显示l
的值,也就是:[0, 1, 2, 3]
所以当你执行
>>> [fun(i) for i in [0, 1, 2, 3]]
这会调用 fun(0)、fun(1) 等,并显示 executed
,然后显示计算值:[0, 1, 2, 3]
这个上下文中的方括号形成一个新列表,其中每个元素都是[0,1,2,3]中相应元素的函数fun。它被称为清单
list-comprehensions。 “executed”被打印出来是因为在形成新列表的过程中调用了 fun 函数(对于 [0, 1, 2, 3] 中的每个元素)。数字 0、1、2 和 3 没有打印出来,因为 fun 的 return 值没有打印出来,而是放在新列表中。
要查看新列表:
print("new list:",[fun(i) for i in [0, 1, 2, 3]])
>>> def fun(i):
... print "executed"
... return i
...
这不是短路的例子。这是 具有副作用的函数 - 它确实写入标准输出,除了返回值之外,这是可以观察到的效果。
[fun(i) for i in [0, 1, 2, 3]]
这是list
理解。一般来说,你应该有充分的理由在这种地方使用有副作用的函数,PEP 202 解释 list
理解的动机如下:
List comprehensions provide a more concise way to create lists in
situations where map()
and filter()
and/or nested loops would
currently be used.
因此阅读您的代码的人可能会认为它必须只是创建列表,没有在此操作期间打印元素。
我刚开始学习 Python。我从 here 看到了一段有趣的代码,作者用来解释短路。代码如下:
>>> def fun(i):
... print "executed"
... return i
...
我试着调用 fun(1)。输出如下,对我来说很有意义。
>>> fun(1)
executed
1
然后我尝试了 [fun(i) for i in [0, 1, 2, 3]]
,输出如下所示:
>>> [fun(i) for i in [0, 1, 2, 3]]
executed
executed
executed
executed
[0, 1, 2, 3]
我期待这样的事情:
executed
0
executed
1
executed
2
executed
3
谁能告诉我我做错了什么?谢谢!
试试
l = [fun(i) for i in [0, 1, 2, 3]]
这将输出
executed
executed
executed
executed
然后就执行l
,这样会显示l
的值,也就是:[0, 1, 2, 3]
所以当你执行
>>> [fun(i) for i in [0, 1, 2, 3]]
这会调用 fun(0)、fun(1) 等,并显示 executed
,然后显示计算值:[0, 1, 2, 3]
这个上下文中的方括号形成一个新列表,其中每个元素都是[0,1,2,3]中相应元素的函数fun。它被称为清单 list-comprehensions。 “executed”被打印出来是因为在形成新列表的过程中调用了 fun 函数(对于 [0, 1, 2, 3] 中的每个元素)。数字 0、1、2 和 3 没有打印出来,因为 fun 的 return 值没有打印出来,而是放在新列表中。 要查看新列表:
print("new list:",[fun(i) for i in [0, 1, 2, 3]])
>>> def fun(i):
... print "executed"
... return i
...
这不是短路的例子。这是 具有副作用的函数 - 它确实写入标准输出,除了返回值之外,这是可以观察到的效果。
[fun(i) for i in [0, 1, 2, 3]]
这是list
理解。一般来说,你应该有充分的理由在这种地方使用有副作用的函数,PEP 202 解释 list
理解的动机如下:
List comprehensions provide a more concise way to create lists in situations where
map()
andfilter()
and/or nested loops would currently be used.
因此阅读您的代码的人可能会认为它必须只是创建列表,没有在此操作期间打印元素。