[英]What is the meaning of print()[] in Python?
>>> print("Approved","Summer School","Failed")[0]
Approved
>>> print("Approved","Summer School","Failed")[1]
Summer School
>>> print("Approved","Summer School","Failed")[2]
Failed
See the pattern? 看模式? It's just simple indexing. 它只是简单的索引。
By the way we always know (g<7)+(g<3)
will be >= 0
( False + False
) and <= 2
( True + True
). 顺便说一下,我们总是知道(g<7)+(g<3)
将>= 0
( False + False
)和<= 2
( True + True
)。
Recall that bool
is a subclass of int
, and that True == 1
and False == 0
(which is why we can add bool
s, as is done above). 回想一下bool
是int
的子类,而True == 1
和False == 0
(这就是我们可以添加bool
的原因,如上所述)。
Finally, it goes without saying that this confusion could have easily been avoided with an extra set of parenthesis: 最后,不言而喻,通过一组额外的括号可以很容易地避免这种混淆:
print(("Approved","Summer School","Failed")[(g<7)+(g<3)])
It's just tuple indexing. 它只是元组索引。 No different from this: 与此无异:
x = (1, 2, 3)[1]
which assigns 2
to x
. 它将2
分配给x
。
In your more complex variant, an element of the tuple is selected and then passed to print
. 在更复杂的变体中,选择元组的元素然后传递给print
。
The confusion is that the code makes it look like you are calling a function named print
. 令人困惑的是,代码使得它看起来像是在调用名为print
的函数。 This confusion was removed in Python 3 by dint of print
being turned into a function. 在Python 3中通过将print
转换为函数来消除这种混淆。 The code in your question does something utterly different in Python 3. 你的问题中的代码在Python 3中完全不同。
print(x,y,...)[i]
should be parsed as print (x,y)[i]
. print(x,y,...)[i]
应解析为print (x,y)[i]
。 Its just print followed by tuple
. 它只是打印后跟tuple
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.