奇怪的 python 语法,它是如何工作的,它叫什么?
print max(3 for i in range(4))
#output is 3
使用 Python 2.6
The 3 让我很失望,这是我尝试解释发生的事情。
for i in range(4) 生成一个循环 4 次的循环,在每次循环开始时将 i 从 0 递增到 3。 [不知道 3 在这种情况下意味着什么...] max() 返回传递给它的最大可迭代对象,并将结果打印到屏幕上。
print max(3 for i in range(4))
#output is 3
Using Python 2.6
The 3 is throwing me off, heres my attempt at explaining whats going on.
for i in range(4) makes a loop that loops 4 times, incrementing i from 0 to 3 at the start of each loop. [no idea what the 3 means in this context...] max() returns the biggest iterable passed to it and the result is printed to screen.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
3 for i in range(4)
是一个生成器,它连续四次生成 3,而max
接受一个可迭代对象并返回具有最高值的元素,即,显然,这里是三个。3 for i in range(4)
is a generator that yields 3 four times in a row andmax
takes an iterable and returns the element with the highest value, which is, obviously, three here.其计算结果为:
...这是
print 3
的详细表达方式。expr for x in xs
是一个生成器表达式。通常,您会在expr
中使用x
。例如:This evaluates to:
... which is an elaborate way to say
print 3
.expr for x in xs
is a generator expression. Typically, you would usex
inexpr
. For example:它可以重写为:
我希望这使它的毫无意义更加明显。
It can be rewritten as:
I hope that makes its pointlessness more obvious.
表达式:
打印 max() 函数的结果,应用于括号内的内容。然而,在括号内,您有一个生成器表达式创建类似于数组的东西,所有元素都等于
3
,但比表达式更有效:创建一个
3
数组,并在不再需要时将其销毁。基本上:因为在括号内您将仅创建相等的值,并且
max()
函数返回最大的值,因此您不需要创建多个元素。因为元素数量始终等于 1,所以不需要max()
函数,并且您的代码可以有效地替换为以下代码(至少在您给出的情况下):即简单地说;)
要详细了解理解和生成器表达式之间的差异,您可以访问此文档页面。
The expression:
is printing the result of the
max()
function, applied to what is inside the parentheses. Inside the parentheses however, you have a generator expression creating something similar to an array, with all elements equal to3
, but in a more efficient way than the expression:which will create an array of
3
s and destroy it after it is no longer needed.Basically: because inside the parentheses you will create only values that are equal, and the
max()
function returns the biggest one, you do not need to create more than one element. Because with the number of elements always equal to one, themax()
function becomes not needed and your code can be effectively replaced (at least in the case you have given) by the following code:That is simply all ;)
To read more about differences between comprehension and generator expression, you can visit this documentation page.