python排序方法实例分析
本文实例讲述了python排序方法。分享给大家供大家参考。具体如下:
>>> def my_key1(x): ... return x % 10 ... >>> alist = [4, 5, 8, 1, 63, 8] >>> alist [4, 5, 8, 1, 63, 8] >>> alist.sort() # 默认升序排序 >>> alist [1, 4, 5, 8, 8, 63] >>> alist.sort(reverse = True) # 改为降序排序 >>> alist [63, 8, 8, 5, 4, 1] >>> alist.sort(key = my_key1) # 设置排序的key值 >>> alist [1, 63, 4, 5, 8, 8] >>> >>> def my_key2(x): ... return x[1] ... >>> alist = [(5,'a'),(1,'w'),(2,'e'),(6,'f')] >>> alist.sort(key = my_key2) # 根据每个元组的第二分量进行排序 >>> alist [(5, 'a'), (2, 'e'), (6, 'f'), (1, 'w')] >>>
希望本文所述对大家的Python程序设计有所帮助。