Python列表cmp()方法

Python列表cmp()方法比較兩個列表。

語法

以下是cmp()方法的語法 -

cmp(list1, list2)

參數

  • list1 - 這是要比較的第一個列表。
  • list2 - 這是第二個要比較的列表。

返回值

  • 如果元素的類型相同,則執行比較並返回結果。如果元素是不同的類型,則檢查它們是否是數字。
    • 如果數字,必要時進行數字強制比較。
    • 如果任一元素是數字,則另一個元素是“較大的”(數字值“最小”)。
    • 否則,類型按名稱按字母順序排序。

如果到達其中一個列表的末尾,則較長的列表是“較大的”。 如果排除兩個列表並共用相同的數據,結果返回0
如果 list1 < list2 返回 -1, 如果 x == y 返回 0, 如果 list > list2 返回 1

示例

以下示例顯示了cmp()方法的用法。

#!/usr/bin/python3

list1, list2 = [123, 'xyz'], [456, 'abc']

print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)

當運行上面的程式,它產生以下結果 -

-1
1
-1

注意:在python3中,不能使用這個函數

查看python的幫助文檔,在oprater這個模組中有了這麼幾個函數 -

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)

這幾個函數就是用來替換之前的cmp(),之前使用cmp的同胞們,以後就換上面這些函數。
下麵簡單說下這幾個函數的意思 -

lt(a, b) 相當於 a < b
le(a,b) 相當於 a <= b
eq(a,b) 相當於 a == b
ne(a,b) 相當於 a != b
gt(a,b) 相當於 a > b
ge(a, b)相當於 a>= b


上一篇: Python列表 下一篇: Python元組