2013-04-26 110 views
0

我不断收到此错误'list' object has no attribute 'priority',我不知道如何解决它。Python得到奇怪的错误

这里是我的代码的一部分,我不能在这里展示这一切为我的项目:

def Tree(self): 

    while len(self.heap) > 0: 
     leftChild= self.heap.pop(0) 
     rightChild= self.heap.pop(0) 
     a = leftChild.priority + rightChild.priority 
     parent = [(leftChild.item + rightChild.item, a)] 
     print parent 
     #self.heap.insert(0, parent) 
    #return self.heap[0] 

所以基本上我有一个优先级队列列表,我经过的每个元素堆是一个列表。然后我弹出每个项目,每个leftChildrightChild应该有,例如:[("c", 0.1231)]它运行良好,并打印父级,直到我运行显示错误消息的插入功能。任何人都知道我做错了什么?

+0

'left'或'leftChild'?你真的需要打定主意。 – paxdiablo 2013-04-26 04:21:33

+0

其leftchild和rightchild – 2013-04-26 04:22:57

+1

'leftChild'和'rightChild'从哪里来? – mgilson 2013-04-26 04:23:02

回答

1

如果它抱怨没有priority属性的列表,那么可以肯定的是,堆中出来的东西(例如leftChild)是列表而不是某种“节点”。

请确保您插入从原来的列表,这些节点到您堆的东西,如:

self.heap.insert (myList[4])  # an item in the list 

而不是:

self.heap.insert (myList[4:5]) # a sublist of the list. 

你可以尝试打印type(leftChild)找出实际的类型它是,根据以下成绩单:

$ python 
Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01) 
[GCC 4.3.4 20090804 (release) 1] on cygwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> x = [1,2,3,4,5,6,7] 

>>> x1 = x[4] 

>>> x2 = x[4:5] 

>>> x1 
5 

>>> x2 
[5] 

>>> type(x1) 
<type 'int'> 

>>> type(x2) 
<type 'list'> 
+0

,但我不明白为什么它打印第一个父母,然后它说错误。所以在父母leftChild.priority工作,但不是在插入功能? – 2013-04-26 04:31:44

+0

当我在这里输入它出来 2013-04-26 04:35:17

+0

@TommyNgo,那么,你有它。堆中的东西是列表而不是“节点”。你需要找到插入它们并修复它的代码。 – paxdiablo 2013-04-26 04:44:27