使用 Python 中的 heapq 模組合併兩個已排序陣列?
在本節中,我們將瞭解如何使用 Python 中的 heapq 模組合併兩個已排序列表。例如,如果 list1 = [10, 20, 30, 40] 並且 list2 = [100, 200, 300, 400, 500],則合併後將返回 list3 = [10, 20, 30, 40, 100, 200, 300, 400, 500]。
為了執行此任務,我們將使用 heapq 模組。此模組作為標準庫模組隨 Python 一起提供。因此,我們需要在使用它之前匯入它。
import heapq
heapq 模組具有一些屬性。它們如下所示:
方法 heapq.heapify(iterable)
它用於將可迭代資料集轉換為堆資料結構。
方法 heapq.heappush(heap, element)
此方法用於將元素插入堆中。之後重新堆化整個堆結構。
方法 heapq.heappop(heap)
此方法用於返回並從堆頂刪除元素,並在其餘元素上執行堆化。
方法 heapq.heappushpop(heap, element)
此方法用於在一個語句中插入和彈出元素。
方法 heapq.heapreplace(heap, element)
此方法用於在一個語句中插入和彈出元素。它從堆的根節點刪除元素,然後將元素插入堆中。
方法 heapq.nlargest(n, iterable, key=None)
此方法用於從堆中返回 n 個最大元素。
方法 heapq.nsmallest(n, iterable, key=None)
此方法用於從堆中返回 n 個最小元素。
示例程式碼
import heapq
first_list = [45, 12, 63, 95, 74, 21, 20, 15, 36]
second_list = [42, 13, 69, 54, 15]
first_list = sorted(first_list)
second_list = sorted(second_list)
print('First sorted list: ' + str(first_list))
print('Second sorted list: ' + str(second_list))
final_list = list(heapq.merge(first_list, second_list))
print('The final list: ' + str(final_list))輸出
First sorted list: [12, 15, 20, 21, 36, 45, 63, 74, 95] Second sorted list: [13, 15, 42, 54, 69] The final list: [12, 13, 15, 15, 20, 21, 36, 42, 45, 54, 63, 69, 74, 95]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP