在本篇內容裏小編給大家整理了關於Python List cmp()用法相關知識點,有需要的朋友們跟着學習下。
描述
cmp() 方法用於比較兩個列表的元素。
語法
cmp()方法語法:
cmp(list1, list2)
參數
list1 -- 比較的列表。
list2 -- 比較的列表。
返回值
如果比較的元素是同類型的,則比較其值,返回結果。
如果兩個元素不是同一種類型,則檢查它們是否是數字。
- 如果是數字,執行必要的數字強制類型轉換,然後比較。
- 如果有一方的元素是數字,則另一方的元素"大"(數字是"最小的")
- 否則,通過類型名字的字母順序進行比較。
如果有一個列表首先到達末尾,則另一個長一點的列表"大"。
如果我們用盡了兩個列表的元素而且所 有元素都是相等的,那麼結果就是個平局,就是說返回一個 0。
實例
以下實例展示了 cmp()函數的使用方法:
#!/usr/bin/python list1, list2 = [123, 'xyz'], [456, 'abc'] print cmp(list1, list2); print cmp(list2, list1); list3 = list2 + [786]; print cmp(list2, list3)
以上實例輸出結果如下:
-1
1
-1
Python 3.X 的版本中已經沒有 cmp 函數,如果你需要實現比較功能,需要引入 operator 模塊,適合任何對象,包含的方法有:
operator.lt(a, b) operator.le(a, b) operator.eq(a, b) operator.ne(a, b) operator.ge(a, b) operator.gt(a, b) operator.__lt__(a, b) operator.__le__(a, b) operator.__eq__(a, b) operator.__ne__(a, b) operator.__ge__(a, b) operator.__gt__(a, b)
實例
>>> import operator >>> operator.eq('hello', 'name'); False >>> operator.eq('hello', 'hello'); True
3.0 版本開始沒這個函數了,官方文檔是這麼寫的:
The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)