【发布时间】:2011-12-09 19:52:05
【问题描述】:
我正在使用 python2.6。它在更高版本的python中可用吗?
否则还有其他方法可以维护非平凡类对象列表的优先级队列吗?
我需要的是这样的
>>> l = [ ['a', 3], ['b', 1] ]
>>> def foo(x, y):
... return x[1]-y[1]
>>> heap = heapify(l, cmp=foo)
有什么建议吗?
【问题讨论】:
标签: python
我正在使用 python2.6。它在更高版本的python中可用吗?
否则还有其他方法可以维护非平凡类对象列表的优先级队列吗?
我需要的是这样的
>>> l = [ ['a', 3], ['b', 1] ]
>>> def foo(x, y):
... return x[1]-y[1]
>>> heap = heapify(l, cmp=foo)
有什么建议吗?
【问题讨论】:
标签: python
传统的解决方案是将(优先级,任务)元组存储在堆上:
pq = [ ]
heappush(pq, (10, task1))
heappush(pq, (5, task2))
heappush(pq, (15, task3))
priority, task = heappop(pq)
只要没有两个任务具有相同的优先级,这就可以正常工作;否则,将比较任务本身(这在 Python 3 中可能根本不起作用)。
常规文档提供了有关如何使用 heapq 实现优先级队列的指导:
http://docs.python.org/library/heapq.html#priority-queue-implementation-notes
【讨论】:
np.arrays时,这也会造成麻烦,在比较时不会产生布尔值
只需为列表中的对象编写适当的__lt__ 方法,以便它们正确排序:
class FirstList(list):
def __lt__(self, other):
return self[0] < other[0]
lst = [ ['a', 3], ['b', 1] ]
lst = [FirstList(item) for item in lst]
Python 只需要__lt__ 进行排序,但最好定义所有比较或使用functools.total_ordering。
您可以通过使用具有相同第一个值和不同第二个值的两个项目来看到它正在工作。无论第二个值是什么,当您heapify 时,这两个对象都会交换位置,因为lst[0] < lst[1] 将始终是False。如果您需要heapify 稳定,则需要进行更复杂的比较。
【讨论】:
@functools.total_ordering 以轻松支持所有六种操作是微不足道的。 FWIW,PEP 8 建议确实适用于使用堆的内容。 __lt__() 的使用是特定于实现的细节,可能会发生变化。不久前,它改为调用 __le__()。
嗯,这太可怕了,你绝对不应该这样做……但它看起来像 heapq 模块 defines a cmp_lt function,如果你真的想要一个自定义比较函数,你可以对其进行修补。
【讨论】:
heapq 模块的代码,并且可怕会破坏任何其他试图猴子修补heapq 模块。最好听从 Raymond Hettinger 的建议,他是许多 Python 模块的作者,这些模块实现了类似的算法。
我不知道这是否更好,但它就像 Raymond Hettinger 的解决方案,但优先级是由对象确定的。
让它成为你的对象,并且你想按 x 属性排序。
class Item:
def __init__(self, x):
self.x = x
然后有一个应用配对的函数
def create_pairs(items):
return map(lambda item: (item.x, item), items)
然后将该函数应用于列表作为 heapq.merge 的输入
list(heapq.merge(create_pairs([Item(1), Item(3)]),
create_pairs([Item(2), Item(5)])))
这给了我以下输出
[(1, <__main__.Item instance at 0x2660cb0>),
(2, <__main__.Item instance at 0x26c2830>),
(3, <__main__.Item instance at 0x26c27e8>),
(5, <__main__.Item instance at 0x26c2878>)]
【讨论】:
通过这些Heap 和HeapBy 类,我试图简化heapq 的使用。可以使用HeapBy传递一个key排序函数。
请注意,Raymond 说如果优先级重复并且值不可排序,他的solution 将不起作用。这就是为什么我添加了一个带有 NonComparable 类的 HeapBy 示例。
我从agf's solution 那里得到了__lt__ 的想法。
用法:
# Use HeapBy with a lambda for sorting
max_heap = HeapBy(key=lambda x: -x)
max_heap.push(3)
max_heap.push(1)
max_heap.push(2)
assert max_heap.pop() == 3
assert max_heap.pop() == 2
assert max_heap.pop() == 1
# Use Heap as a convenience facade for heapq
min_heap = Heap()
min_heap.push(3)
min_heap.push(1)
min_heap.push(2)
assert min_heap.pop() == 1
assert min_heap.pop() == 2
assert min_heap.pop() == 3
# HeapBy also works with non-comparable objects.
# Note that I push a duplicated value
# to make sure heapq will not try to call __lt__ on it.
class NonComparable:
def __init__(self, val):
self.val = val
# Using non comparable values
max_heap = HeapBy(key=lambda x: -x.val)
max_heap.push(NonComparable(1))
max_heap.push(NonComparable(1))
max_heap.push(NonComparable(3))
max_heap.push(NonComparable(2))
assert max_heap.pop().val == 3
assert max_heap.pop().val == 2
assert max_heap.pop().val == 1
assert max_heap.pop().val == 1
类:
import heapq
class Heap:
"""
Convenience class for simplifying heapq usage
"""
def __init__(self, array=None, heapify=True):
if array:
self.heap = array
if heapify:
heapq.heapify(self.heap)
else:
self.heap = []
def push(self, x):
heapq.heappush(self.heap, x)
def pop(self):
return heapq.heappop(self.heap)
class HeapBy(Heap):
"""
Heap where you can specify a key function for sorting
"""
# Item only uses the key function to sort elements,
# just in case the values are not comparable
class Item:
def __init__(self, value, key):
self.key = key
self.value = value
def __lt__(self, other):
return self.key(self.value) < other.key(other.value)
def __init__(self, key, array=None, heapify=True):
super().__init__(array, heapify)
self.key = key
def push(self, x):
super().push(self.Item(x, self.key))
def pop(self):
return super().pop().value
【讨论】: