• 技术文章 >Python技术 >Python基础教程

    python如何使用merge实现堆

    小妮浅浅小妮浅浅2021-05-31 09:46:56原创2144

    1、说明

    对于较大的数据集,将会占用大量内存。不是对整个组合序列进行排序,而是使用 merge() 一次生成一个新序列。

    2、实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    import heapq

    import random

      

      

    random.seed(2016)

      

    data = []

    for i in range(4):

        new_data = list(random.sample(range(1, 101), 5))

        new_data.sort()

        data.append(new_data)

      

    for i, d in enumerate(data):

        print('{}: {}'.format(i, d))

      

    print('\nMerged:')

    for i in heapq.merge(*data):

        print(i, end=' ')

    print()

      

    # output

    # 0: [33, 58, 71, 88, 95]

    # 1: [10, 11, 17, 38, 91]

    # 2: [13, 18, 39, 61, 63]

    # 3: [20, 27, 31, 42, 45]

    #

    # Merged:

    # 10 11 13 17 18 20 27 31 33 38 39 42 45 58 61 63 71 88 91 95

    因为merge()使用堆的实现,它根据被合并的序列元素个数消耗内存,而不是所有序列中的元素个数。

    以上就是python使用merge实现堆的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python merge
    上一篇:python bin是什么 下一篇:python namedtuple如何定义数据类型

    相关文章推荐

    • python from…import的导入注意• python中__name__调用模块• dir()函数在python模块的使用• python可变参数的使用注意• python新式类是什么• python响应头部是什么

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网