实现一个迭代器能够生成从1到n之间的所有整数但要跳过其中所有包含数字9的整数Python
的实现如下:
class SkipNineIterator:
def __init__(self, n):
self.n = n
self.current = 1
def __iter__(self):
return self
def __next__(self):
while self.current <= self.n:
if '9' not in str(self.current):
result = self.current
self.current += 1
return result
else:
self.current += 1
else:
raise StopIteration()
使用方法:
for i in SkipNineIterator(20):
print(i)
输出:
1
2
3
4
5
6
7
8
10
11
12
13
14
15
16
17
18
20
原文地址: https://www.cveoy.top/t/topic/bt1j 著作权归作者所有。请勿转载和采集!