Files
Python_CookBook_repo/4.迭代器与生成器/15.合并多个有序序列,再对整个有序序列进行迭代.py
2025-09-10 16:12:45 +08:00

18 lines
628 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import heapq
from itertools import chain
if __name__ == '__main__':
a = [1, 4, 7, 10]
b = [2, 5, 6, 11]
# 首先复习一下前面的知识如果不考虑合并后也是有序的用chain
for item in chain(a, b):
print(item)
# 但如果我们想要得到有序合并序列那就要用堆自带的merge功能了利用小根堆的特殊性来排序
new_arr = heapq.merge(a, b)
for item in new_arr:
print(item)
# 记住heapq的merge事先不会对输入可迭代对象的有序性进行检查而是每次从可迭代对象序列里取出最小的第一个进堆