python序列类型排序
目录
- list.sort方法与内置函数sorted
- bisect模块
- 用bisect.bisect搜索
- 用bisect.insort插入新元素
list.sort方法与内置函数sorted
- list.sort就地排序列表,返回值None,此是python惯例,就地操作的方法返回None。比如random.shuffle。
- 内置函数sorted排序后返回一个列表,sorted接受任何形式的可迭代对象作为参数,但返回值都是列表。
- list.sort和sorted函数都有两个可选参数,reverse和key。
- reverse如果设置为True,则会降序排列。
- key必须是一个只接受一个参数的函数,对序列排序时会把序列中的每个元素都传入key进行运算,运算结果是排序算法依赖的对比关键字。
bisect模块
bisect模块中主要有两个函数,bisect和insort,两个函数都利用二分查找法在有序序列中查找或插入元素。
用bisect.bisect搜索
格式为:
position = bisect.bisect(haystack, needle)
import bisect
haystack = [1, 4, 5, 6, 8, 12, 15, 20]
needle = 4
position = bisect.bisect(haystack, needle)
- haystack是一个排序好的序列,needle是待查找的值,返回值position是一个索引值。position之前索引处的数字均小于needle。
- bisect.bisect有两个可选参数用于选定搜索的范围,lo默认是0,hi默认是序列长度。
- bisect函数其实是bisect_right的别名,还有一个姊妹函数bisect_left,bisect_right返回值是第一个大于needle的值的索引,bisect_left则返回第一个小于等于needle的值的索引。
用bisect.insort插入新元素
格式为:
insort(seq, item)
- seq是排好序的序列,item是要插入的元素。
- insort也有两个可选参数控制查找范围,即lo和hi。
- 用insort插入相当于先用bisect查找位置索引,再用insert插入。
- insort也有个变体insort_left。该变体背后使用besect_left搜索插入索引。