有没有办法在python中追加对象?优先级队列

问题描述 投票:-1回答:2

目前我在enQueue函数中遇到错误。当我尝试在我的对象列表中附加一个数字时,它表示“'set'对象没有属性'append'”。我认为问题与我如何在列表中传递有关,但这是我目前的问题。我有一个大小为10的硬编码列表,因为在我知道发生了什么之前我不想写一个更大的列表。任何帮助,将不胜感激。我在代码中的注释也是我想要做的最终结果。如果你有任何意见,那将是非常有帮助的。目前,我想弄清楚如何得不到这个错误。谢谢。

class PQ_List(object):

    def __init__(self, sampleList):
        print ("creates an unsorted list from passed in list")
        self.list = sampleList
        print (self.list)
#      
#        Returns the list 

    def enQueue(self, item):
        print ("adds an item to the PQ")
        self.list.append(item)
        print (self.list)
#       Add an item to the PQ 

    def deQueue(self):
        print ("removes the highest priority item from the PQ")
        self.list = self.list[1:]
        print (self.list)
#       Remove the highest priority item from the PQ 


    def sneakAPeek(self):
        print ("returns the highest priority in the PQ, but does not remove it")
        return self.list[0]
#
#       Return the highest priority item from the PQ, but don't remove it

    def isEmpty(self):
        print ("returns T if PQ is empty, F if PQ has entries")
        if len(self.list) > 0:
            return 'F'
        else:
            return 'T'
#       Return a T if PQ is empty, F if PQ is not empty 
#       
    def size(self):
        print ("returns number of items in queue")
        return len(self.list)
#       Return the number of items in the queue

sampleList = {1, 2, 5, 8, 4, 15, 13, 12, 10, 6}

my_listPQ = PQ_List(sampleList) #print first 10 numbers, use size to prove the rest is there
my_listPQ.enQueue(1500)
my_listPQ.deQueue()
my_listPQ.sneakAPeek()
my_listPQ.isEmpty()
my_listPQ.size()

我希望输出添加1500到enQueue函数的列表。然后执行以下功能。任何帮助,将不胜感激!

python list priority-queue implementation
2个回答
1
投票

在python中,你使用方括号[]作为列表,使用大括号{}作为集合。

因此,改变线

sampleList = {1, 2, 5, 8, 4, 15, 13, 12, 10, 6}

sampleList = [1, 2, 5, 8, 4, 15, 13, 12, 10, 6]

你很高兴。


0
投票

更改

sampleList = {1, 2, 5, 8, 4, 15, 13, 12, 10, 6}  # this is set and don't have append

到这一个:

sampleList = [1, 2, 5, 8, 4, 15, 13, 12, 10, 6]  # this is list
© www.soinside.com 2019 - 2024. All rights reserved.