简体   繁体   中英

How to return list of tuples in priority order (Python)

After my previous issue ( Priority function for Priority Queue not returning string in Python ), I am struggling to return a tuple in this way: [(1,2), (8,5), (3,4), (1,1)], etc.

class PQElement:
    def __init__(self, v, p):
        self.val = v
        self.priority = p
            
    def __str__(self):
        return "("+str(self.val)+","+str(self.priority)+")"
        
class PQueue:
    def __init__(self):
        self.inList = []
        
    def __len__(self):
        return len(self.inList)

    def ___str__(self,):
        return str(self.inList)
    
    def enq(self, e): # insert (tail)
        self.inList.append(e)   
        
    def deq(self): # remove
        if len(self)==0:
            raise IndexError("deq from empty queue")
        max_priority = self.inList[0].priority
        max_idx = 0
        for idx, elmt in enumerate(self.inList):
            if elmt.priority > max_priority:
                max_priority = elmt.priority
                max_idx = idx
        return self.inList.pop(max_idx)

Added code:

ls = PQueue()
print(ls)
for i in range(15):
    ls.enq(PQElement(i,10-i))
print(ls)
print(ls.deq(),ls)

Not sure where the issue is. Seems you only need a list comprehension.

tuples = [(pq.val,pq.priority) for pq in ls.inList]

If you want then sorted in descending priority order, you can sort the result:

tuples = sorted(tuples,key=lambda t: -t[1])

also, your deq function (in the original question) could be made shorter:

def deq(self): # remove
    if len(self)==0:
        raise IndexError("deq from empty queue")
    i,_ = max(enumerate(self.inList),key=lambda ipq:ipq[1].priority)
    return self.inlist.pop(i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM