【发布时间】:2021-01-25 05:16:27
【问题描述】:
我正在尝试递归遍历我的所有节点,但是我得到了一个无限循环。
class Dictionary:
# STARTS CLASS NODE ################################################
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.nextNode = None
def insert(self, key, value):
if self.nextNode is None or key < self.nextNode.key:
new = Dictionary.Node(key, value)
new.nextNode = self.nextNode
self.nextNode = new
elif key > self.nextNode.key:
self.nextNode.insert(key, value)
else:
pass
def __iter__(self):
if self.nextNode is None:
return self
else:
return self.__next__().__iter__()
def __next__(self):
return self.nextNode
def __str__(self):
return f'{self.key} : {self.value}'
# ENDS CLASS NODE ################################################
def __init__(self):
self.__head = None
def insert(self, key, value):
if self.__head is None or key < self.__head.key:
new = self.Node(key, value)
new.nextNode = self.__head
self.__head = new
elif key > self.__head.key:
self.__head.insert(key, value)
else:
pass
def __iter__(self):
return self.__head
def __str__(self):
return str(self.__head)
d = Dictionary()
d.insert(2, 2)
d.insert(3, 3)
d.insert(4, 4)
d.insert(5, 5)
当我这样做时:
p = iter(d)
print(p)
print(next(p))
print(next(next(p))
它有效,但当我这样做时
for i in p:
print(i)
我得到一个打印 3s 的无限循环。它甚至不跳转节点。
for 循环与执行 iter() 然后多次使用 next() 直到遇到条件(无)不一样吗?我不应该得到同样的东西吗?我做错了什么?
【问题讨论】:
-
迭代器是一个你反复调用
next的对象,它给你一个元素序列,直到它引发一个异常来表示它已经完成。您的__next__实现只会在每次调用时返回self.nextNode。它永远不会引发异常,因此没有信号表明迭代已完成。 -
为什么我们会在你的帖子中看到 2 个方法 init、str、insert ?请编辑并清理代码
-
@azro 主要问题是:为什么在另一个类的上下文中定义一个类?这很不寻常。
标签: python class iteration nodes