python中List的sort方法(或者sorted内建函数)的用法
生活随笔
收集整理的這篇文章主要介紹了
python中List的sort方法(或者sorted内建函数)的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
參考:
http://gaopenghigh.iteye.com/blog/1483864
一直用的方法很土,
class term(object):def __init__(self, sent , score):self.sent = sentself.score = scoredef CMP(t1, t2):if t1.score < t2.score:return -1elif t1.score == t2.score:return 0else:return 1 ls.sort(CMP,reverse = True)要注意,sort的排序是inplace, sorted是返回一個排序后的list,原list不變
List的元素可以是各種東西,字符串,字典,自己定義的類等。?
sorted函數用法如下:?
其中,data是待排序數據,可以使List或者iterator, cmp和key都是函數,這兩個函數作用與data的元素上產生一個結果,sorted方法根據這個結果來排序。?
cmp(e1, e2) 是帶兩個參數的比較函數, 返回值: 負數: e1 < e2, 0: e1 == e2, 正數: e1 > e2. 默認為 None, 即用內建的比較函數.?
key 是帶一個參數的函數, 用來為每個元素提取比較值. 默認為 None, 即直接比較每個元素.?
通常, key 和 reverse 比 cmp 快很多, 因為對每個元素它們只處理一次; 而 cmp 會處理多次.?
通過例子來說明sorted的用法:?
1. 對由tuple組成的List排序?
Python代碼??
用key函數排序(lambda的用法見 注釋1)?
Python代碼??
用cmp函數排序?
Python代碼??
用 operator 函數來加快速度, 上面排序等價于:(itemgetter的用法見 注釋2)?
Python代碼??
用 operator 函數進行多級排序?
Python代碼??
2. 對由字典排序?
Python代碼??
注釋1?
參考:http://jasonwu.me/2011/10/29/introduce-to-python-lambda.html?
注釋2?
參考:http://ar.newsmth.net/thread-90745710c90cf1.html?
class itemgetter(__builtin__.object)?
|? itemgetter(item, ...) --> itemgetter object?
|?
|? Return a callable object that fetches the given item(s) from its operand.?
|? After, f=itemgetter(2), the call f(r) returns r[2].?
|? After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])?
相當于?
Python代碼??
總結
以上是生活随笔為你收集整理的python中List的sort方法(或者sorted内建函数)的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python学习笔记一:数据类型转换
- 下一篇: python中set集合如何决定是否重复