In [1]: a = [7, 2, 5, 1, 3]
In [2]: a.sort()
In [3]: a
Out[3]: [1, 2, 3, 5, 7]
sort也有一些选项
In [4]: b = ['saw', 'small', 'He', 'foxes', 'six']
In [5]: b.sort(key = len)
In [6]: b
Out[6]: ['He', 'saw', 'six', 'small', 'foxes']
bisect模块实现了二分搜索和已排序列表的插值。bisect.bisect
找到应当被插入的位置bisect.insort
将原始插到相应位置。
In [7]: import bisect
In [8]: c = [1, 2, 2, 2, 3, 4, 7]
In [9]: bisect.bisect(c, 2)
Out[9]: 4
In [10]: bisect.bisect(c, 5)
Out[10]: 6
In [11]: bisect.insort(c, 6)
In [12]: c
Out[12]: [1, 2, 2, 2, 3, 4, 6, 7]