当我遇到此错误时,我正在使用 Python 中的双向链表:
def merge(self,other):
mergedCenter = HealthCenter()
selfPatient = self._head
otherPatient = other._head
print(selfPatient.elem)
print(selfPatient.elem < otherPatient.elem)
while (selfPatient or otherPatient):
if selfPatient.elem < otherPatient.elem:
mergedCenter.addLast(selfPatient.elem)
selfPatient = selfPatient.next
elif selfPatient.elem > otherPatient.elem:
mergedCenter.addLast(otherPatient.elem)
otherPatient = otherPatient.next
else:
mergedCenter.addLast(selfPatient.elem)
selfPatient = selfPatient.next
otherPatient = otherPatient.next
return (mergedCenter)
我得到这个输出:
Abad, Ana 1949 True 0
True
Traceback (most recent call last):
File "main.py", line 189, in <module>
hc3 = hc1.merge(hc2)
File "main.py", line 112, in merge
if selfPatient.elem < otherPatient.elem:
AttributeError: 'NoneType' object has no attribute 'elem'
已经实现了一种比较 .elem 的方法,正如您在第二个打印中可以清楚地看到的那样,但我不明白为什么在第一个条件中它不断中断。
提前致谢。
解决办法: 必须考虑两个 DList 的长度,而不是获得两个值之一“Nonetype”。这解决了更改 AND 的 OR,稍后检查哪个不是“Nonetype”以完成合并
答案 0 :(得分:1)
这检查是否有一个是非无,所以如果一个是,而不是另一个,则进入循环
while (selfPatient or otherPatient)
如果您想访问两个 elem
属性,则 both 都需要为非无,需要您将 or
更改为 and
>
否则,当只有一个为 None 时,您需要在 if 语句之前使用单独的逻辑来处理,然后可能会中断循环以便达到返回值。将现有逻辑的其余部分包装在 if selfPatient and otherPatient
中仍然没有什么坏处,因为您同时使用了两者的属性
至于为什么一个变成None,那要看你迭代链表的逻辑了