FizzBuzz列表理解 [英] FizzBuzz list comprehension
问题描述
当我学习python时,我在搞一些不同的fizz buzz脚本.我遇到了一个效果很好的工具,但是我无法理解它是如何工作的.我知道正常的嘶嘶声蜂鸣如何与for循环一起工作,并且如果i%3 == 0和i%5 == 0".我难过的是"Fizz" ( not i%3 )+" Buzz " (not i%5)" 有效.
I was messing around with some different fizz buzz scripts as I learn python. I came across this one which works great but I can't decipher how it works. I know how the normal fizz buzz works with a for loop and "if i % 3 == 0 and i % 5 == 0". What has me stumped is how "Fizz"(not i%3) + "Buzz"(not i%5)" works.
x = ["Fizz"*(not i%3) + "Buzz"*(not i%5) or i for i in range(1, 100)]
推荐答案
在python中,您可以使用乘法运算符来复制字符串:
In python you can replicate a string by using the multiplication operator:
print('aaa' * 3) # aaaaaaaaa
此外,布尔值在乘法时会隐式转换为整数.因此,如果您这样做
Also, boolean values are implicitly casted to integers on multiplication. Thus, if you do
"Fizz"*(not i%3)
首先,i%3将返回模的结果.然后,如果结果为0,not
运算符会将其转换为True
,否则将其转换为False
(通过将其强制转换为布尔值,然后取负值).然后应用乘法运算符,False
变为0,True
变为1.
First, the i%3 will return the result of the modulo. Then, the not
operator will convert it to either True
if the result was 0, or to False
otherwise (by casting it to boolean and then negating the value). By then applying a multiplication operator, False
turns to 0 and True
turns into 1.
因此,如果数字可被3整除,则求模结果为0,应用not
时为True
,乘为1时,字符串Fizz
被复制1次.乘法.如果不能将其整除,则将0作为乘法的操作数,有效地将字符串Fizz
复制0次,从而得到一个空字符串.
Thus, if the number is divisible by 3, we get 0 as the result of the modulo, True
when applying not
, 1 when multiplying, and the string Fizz
replicated 1 time as the result of the multiplication. If it is not divisible, we get 0 as operand for the multiplication, effectively getting the string Fizz
replicated 0 times, thus an empty string.
Buzz
也是如此,范围中每个i
的结果只是两者的串联.
The same goes for Buzz
, and the result for each i
in the range is just the concatenation of the two.
这篇关于FizzBuzz列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!