3 回答

TA貢獻1788條經驗 獲得超4個贊
與其將元素直接插入隊列,不如將每個元素包裝在一個元組中,其中元組中的第一個元素是所需的排序鍵。元組按其元素的順序排序(即,首先比較第一個元素),因此排序鍵需要排在第一位。
import heapq
queue = []
my_list = [...]
for element in my_list:
heapq.heappush(queue, (my_func(element), element))

TA貢獻1796條經驗 獲得超4個贊
如果您有元素的包裝類,那么您可以使用運算符重載。
例如,假設您有一個CustomNumber類(相當于您的元素),其中順序由模 16 值(私有函數__f())確定,您可以覆蓋比較運算符,例如:
class CustomNumber:
def __init__(self, value):
self.value = value
def __f(self, x):
return x % 16
def __lt__(self, obj):
"""self < obj."""
return self.__f(self.value) < self.__f(obj.value)
def __le__(self, obj):
"""self <= obj."""
return self.__f(self.value) <= self.__f(obj.value)
def __eq__(self, obj):
"""self == obj."""
return self.__f(self.value) == self.__f(obj.value)
def __ne__(self, obj):
"""self != obj."""
return self.__f(self.value) != self.__f(obj.value)
def __gt__(self, obj):
"""self > obj."""
return self.__f(self.value) > self.__f(obj.value)
def __ge__(self, obj):
"""self >= obj."""
return self.__f(self.value) >= self.__f(obj.value)
這樣下面的代碼:
a = CustomNumber(16)
b = CustomNumber(14)
print('a < b =', a < b)
print('a <= b =', a <= b)
print('a == b =', a == b)
print('a != b =', a != b)
print('a > b =', a > b)
print('a >= b =', a >= b)
印刷:
a < b = True
a <= b = True
a == b = False
a != b = True
a > b = False
a >= b = False

TA貢獻1802條經驗 獲得超5個贊
Here is an example of using custom sort in PriorityQueue in Python.
We use a priority-queue (heapq) find the next element to add. To make the
implementation simple we "monkey patch" the ListNode class to have a custom
less-than function using setattr. Note that, simply using the tuple trick
and pushing (node.val, node) to the priority queue will not work because
the lists have values in common.
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
setattr(ListNode, "__lt__", lambda self, other: self.val <= other.val)
pq = []
for l in lists:
if l:
heapq.heappush(pq, l)
out = ListNode(None)
head = out
while pq:
l = heapq.heappop(pq)
head.next = l
head = head.next
if l and l.next:
heapq.heappush( pq, l.next)
return out.next
添加回答
舉報