为什么行得通? [英] Why does it work?
问题描述
因此,我正在学习Python并研究一系列程序思想.当然,我写了强制性的FizzBuzz,它起作用了,但是基本上是其他语言.我用谷歌搜索它是否还有其他方法,并发现了这种潮湿的单线:
So I'm learning Python and working through a list of program ideas. Of course I wrote the obligatory FizzBuzz, which worked, but was basically if elif else blablabla. I googled it to see if there are other ways and found this dank one-liner:
for i in range(1,101):
print("Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) or i)
没有ifs,没有elifs,什么也没有.我用Google搜索了字符串连接",并找到了*符号的信息,但在这种情况下不了解它的工作方式.有人可以解释吗?
There are no ifs, no elifs, nothing. I googled "string concatenation" and found info on the * symbol, but don't understand how it's working in this case. Can somebody explain?
推荐答案
没有ifs,没有elifs,什么也没有.
There are no ifs, no elifs, nothing.
当然有!只是变相.查找字符串连接(即+
)对您没有帮助,因为*
是重复.具体来说,字符串*
n为您提供一个字符串,该字符串是一行中n个字符串的副本.此外,布尔值可以隐式转换为整数:True
变为1
,而False
变为0
.所以
Sure there are! Just disguised. Looking for string concatenation (i.e. +
) won't help you, because *
is repetition. Specifically, string *
n gives you a string that is n copies of string in a row. Further, a boolean value can be implicitly converted to an integer: True
becomes 1
and False
becomes 0
. So
"Fizz" * (i % 3 == 0)
表示如果i % 3 == 0
,则为一个Fizz
,否则为否."与Buzz
相同.
means "One Fizz
if i % 3 == 0
, none if not." Same with Buzz
.
最后,末尾的or i
表示如果由于两个部分都为空而得到空字符串,则改为得到i
. or
的真正含义是除非左侧为假值,否则左侧的值,在这种情况下,将返回右侧的值."
Finally, that or i
at the end means that if you got the empty string because both parts came up empty, then you get i
instead. or
really means "the value of the left hand side unless the left hand side is a false value, in which case return the value of the right hand side."
此技巧也在其他地方使用. Python没有直接等同于C的?:
运算符,但是由于上面提到的布尔到整数转换,您可以使用两个元素的元组和一个索引操作来接近它.所以C的
This trick gets used elsewhere, too. Python doesn't have a direct equivalent to C's ?:
operator, but you can get close to one with a two-element tuple and an index operation because of the bool-to-integer conversion I mentioned above. So C's
a? b: c
表示"b
,如果a
为true,否则为c
"在Python中变为:
which means "b
if a
is true, otherwise c
" becomes this in Python:
(c, b)[a]
这篇关于为什么行得通?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!