• 玩转python标准库,好用的功能梳理


    1.

    当仅通过 print() 输出的行太长,不方便查看时。

    t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
        'yellow'], 'blue']]]
    print(t)
    [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]
    
    • 1
    • 2
    • 3
    • 4

    通过 pprint 中的 width 参数,调整每行的长度。

    import pprint
    t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
        'yellow'], 'blue']]]
    
    pprint.pprint(t, width=30)
    
    [[[['black', 'cyan'],
       'white',
       ['green', 'red']],
      [['magenta', 'yellow'],
       'blue']]]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    2. bisect_left 二分查找

    bisect_leftPython 标准库 bisect 中的一个函数。bisect 模块提供了对排序列表的支持,用来进行二分查找和插入操作。bisect_left 函数用于找到应将一个值插入到已排序列表中的位置,从而使列表保持排序状态。

    函数原型如下:

    bisect.bisect_left(list, num, beg, end)
    
    • 1

    参数说明:

    • list:一个已排序的列表。
    • num:需要插入的值。
    • beg:开始搜索的索引,默认为0。
    • end:结束搜索的索引,默认为列表的长度。

    函数返回值为一个索引,表示在 list 中应该插入 num 的位置,以保持 list 的排序。

    例如,以下代码演示了如何使用 bisect_left 函数:

    import bisect
    
    numbers = [1, 3, 4, 4, 6, 8]
    index = bisect.bisect_left(numbers, 4)
    print(index)  # 输出: 3
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在上面的示例中,bisect_left 函数返回了索引3,表示数字4应该插入到 numbers 列表的索引3的位置,以保持列表的排序。

    import bisect
     
    numbers = [1, 3, 4, 4, 6, 8]
    index = bisect.bisect_left(numbers, 5)
    print(index)  # 输出: 4
    
    4
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    import bisect
    
    numbers = [1, 3, 4, 4, 6, 8]
    index = bisect.bisect_left(numbers, 9)
    print(index)  # 输出: 6
    
    6
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    基于Spring Boot的工具迭代
    MTK 关机充电时充电IC正常,电池正常充电,但是充电动画一直显示0%
    CentOS修改主机名
    零基础入门学习Web开发:HTML篇(一)
    docker:dockerfile构建镜像
    我的世界1.20规则大全,/gamerule最新全部规则解释
    Linux端使用百度网盘命令行工具深度指南
    Selenium基础
    Hadoop虚拟机安装超详细版
    一招教你合并多个视频:详细图文教程
  • 原文地址:https://blog.csdn.net/weixin_46713695/article/details/132896543