Python 为什么迭代器不从初始位置开始
我的自定义迭代器不是从初始位置开始的:Python 为什么迭代器不从初始位置开始,python,python-3.x,Python,Python 3.x,我的自定义迭代器不是从初始位置开始的: class XYpositions: def __init__(self, width, height): self.width = width self.height = height self.pos = (0,0) def __iter__(self): return self def __next__(self): self.pos = (sel
class XYpositions:
def __init__(self, width, height):
self.width = width
self.height = height
self.pos = (0,0)
def __iter__(self):
return self
def __next__(self):
self.pos = (self.pos[0]+1, self.pos[1])
if self.pos[0] >= self.width:
self.pos = (0, self.pos[1]+1)
if self.pos[1] >= self.height:
raise StopIteration
return self.pos
for pos in XYpositions(2, 3):
print(pos)
屈服
(1, 0)
(0, 1)
(1, 1)
(0, 2)
(1, 2)
什么??(0,0)在哪里?正如@Rocket所指出的,每个迭代(包括第一次迭代)都会调用
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
如果希望迭代器从初始化位置开始,则必须先将当前位置保存在\uuuuu next\uuuu
中,然后再按如下方式递增:
def __next__(self):
current_pos = self.pos
self.pos = (self.pos[0]+1, self.pos[1])
if self.pos[0] >= self.width:
self.pos = (0, self.pos[1]+1)
if current_pos[1] >= self.height:
raise StopIteration
return current_pos
应在代码中的何处返回(0,0)?在开始将1添加到self.pos[0]
之前或之后?\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>是为每个迭代调用的,包括第一次。那么为什么tuturial在初始位置初始化(而不是-1)@WurmD注意该示例是如何在增加当前值之前保存它的。loud-facepalm这过早地结束了迭代。您希望最后一个if
块(可以raise
)考虑上一次计算中保存的当前位置,而不是新位置。将其移动到函数顶部,您将得到正确的结果(以1,2
作为最后一个有效输出结尾)。捕捉正确,更正了它