在学习 Python 时,我正在处理一些不同的 fizz buzz 脚本。我遇到了这个效果很好但我无法破译它是如何工作的。我知道正常的 fizz 嗡嗡声如何与 for 循环和“if i % 3 == 0 and i % 5 == 0”一起使用。让我难倒的是“Fizz”(不是 i%3)+“ Buzz ” (不是 i%5)是如何工作的。
x = ["Fizz"*(not i%3) + "Buzz"*(not i%5) or i for i in range(1, 100)]
Run Code Online (Sandbox Code Playgroud) 我试图弄清楚如何让这个类在 Python 3 中工作,它在 Python 2 中工作。这是来自 D. Beasley 的生成器教程。我是 Python 新手,只是在网上学习教程。
蟒蛇 2
class countdown(object):
def __init__(self, start):
self.count = start
def __iter__(self):
return self
def next(self):
if self.count <= 0:
raise StopIteration
r = self.count
self.count -= 1
return r
c = countdown(5)
for i in c:
print i,
Run Code Online (Sandbox Code Playgroud)
Python 3,不工作。
class countdown(object):
def __init__(self, start):
self.count = start
def __iter__(self):
return self
def next(self):
if self.count <= 0:
raise StopIteration
r = self.count
self.count -= 1
return …Run Code Online (Sandbox Code Playgroud)