我在一個程序中發現了一個有趣的錯誤,我有點懶惰地執行,並想知道我是否正確理解它。簡短版本是Python's heapq
implementation實際上並沒有排序列表,它只是以堆爲中心的方式列出列表。具體而言,我期待heapify()
產生一個有序列表,以有序的方式促進列表理解。使用Python的heapify()與列表理解和切片不兼容嗎?
優先提示例如,Python的文檔:
from heapq import heapify, heappush, heappop
from random import shuffle
class Item(object):
def __init__(self, name):
self.name = name
lst = []
# iterate over a pseudo-random list of unique numbers
for i in sample(range(100), 15):
it = Item("Some name for %i" % i)
heappush(lst, (i, it))
print([i[0] for i in lst])
結果
>>> [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67]
此,我們注意到,不在列表的原排序,但顯然一些以堆爲中心的排序爲described here。我正在懶洋洋地期待這完全訂購。
作爲測試,通過heapify()運行列表會導致沒有變化(如列表已經堆ishly訂購):
heapify(lst)
print([i[0] for i in lst])
>>> [2, 22, 7, 69, 32, 40, 10, 97, 89, 33, 45, 51, 94, 27, 67]
而通過與訂貨的heappop()
功能結果的列表迭代預期:
lst2 = []
while lst: lst2.append(heappop(lst))
print([i[0] for i in lst2])
>>> [2, 7, 10, 22, 27, 32, 33, 40, 45, 51, 67, 69, 89, 94, 97]
因此,它似乎heapq
不下令列表(至少在這個詞的人的意義上),而是heappush()
和heappop()
功能能夠饒有興趣地列出堆。
結果:堆積列表上的任何切片和列表理解操作都會產生無序結果。
這是真的,這是總是是真的嗎?
(順便說一句:Python之3.0.1上的WinXP系統)
是的,我主要發佈它,以便在其他人有同樣問題時可用,但很高興知道我誤解了這些文檔,並且應該更清楚地閱讀它們。 – JohnMetta 2009-06-26 14:48:41