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

1.

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

t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
    'yellow'], 'blue']]]
print(t)
[[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', 'yellow'], 'blue']]]

通过 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']]]

2. bisect_left 二分查找

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

函数原型如下:

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

参数说明:

  • 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

在上面的示例中,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
import bisect

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

6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值