Python得到奇怪的错误

时间:2013-04-26 04:15:55

标签: python

我一直收到此错误'list' object has no attribute 'priority',我不知道如何修复它。

以下是我的代码的一部分我不能在这里作为我的项目展示:

    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]

所以基本上我有一个优先级队列列表,我将每个元素传递给一个列表堆。然后我通过pop取出每个项目,每个leftChildrightChild应该有,例如:[("c", 0.1231)]它运行正常并打印父项,直到我运行显示错误消息的插入函数。任何人都知道我做错了什么?

1 个答案:

答案 0 :(得分: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'>
相关问题