用bisect来搜索

bisect(haystack, needle) 在 haystack(干草垛)里搜索 needle(针)的位置,该位置满足的条件是,把 needle 插入这个位置之后,haystack 还能保持升序。也就是在
说这个函数返回的位置前面的值,都小于或等于 needle 的值。其中 haystack 必须是一个有序的序列。你可以先用 bisect(haystack, needle) 查找位置 index,再用
haystack.insert(index, needle) 来插入新值。但你也可用 insort 来一步到位,并且后者的速度更快一些。

import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
  for needle in reversed(NEEDLES):
  position = bisect_fn(HAYSTACK, needle) ➊
  offset = position * ' |' ➋
  print(ROW_FMT.format(needle, position, offset)) ➌
if __name__ == '__main__':
  if sys.argv[-1] == 'left': ➍
    bisect_fn = bisect.bisect_left
  else:
    bisect_fn = bisect.bisect
  print('DEMO:', bisect_fn.__name__) ➎
  print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
  demo(bisect_fn)

❶ 用特定的 bisect 函数来计算元素应该出现的位置。
❷利用该位置来算出需要几个分隔符号。
❸ 把元素和其应该出现的位置打印出来。
❹ 根据命令上最后一个参数来选用 bisect 函数。
❺ 把选定的函数在抬头打印出来

def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
    i = bisect.bisect(breakpoints, score)
    return grades[i]
[grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]

 输出:['F', 'A', 'C', 'C', 'B', 'A', 'A']

原文地址:https://www.cnblogs.com/WhatTTEver/p/7087613.html