描述
cmp() 方法用于比較兩個列表的元素。
語法
cmp()方法語法:
cmp(list1, list2)
參數(shù)
list1 -- 比較的列表。
list2 -- 比較的列表。
返回值
如果比較的元素是同類型的,則比較其值,返回結(jié)果。
如果兩個元素不是同一種類型,則檢查它們是否是數(shù)字。
如果有一個列表首先到達(dá)末尾,則另一個長一點的列表"大"。
如果我們用盡了兩個列表的元素而且所 有元素都是相等的,那么結(jié)果就是個平局,就是說返回一個 0。
實例
以下實例展示了 cmp()函數(shù)的使用方法:
#!/usr/bin/pythonlist1, list2 = [123, 'xyz'], [456, 'abc']print cmp(list1, list2);print cmp(list2, list1);list3 = list2 + [786];print cmp(list2, list3)
以上實例輸出結(jié)果如下:
-1
1
-1
Python 3.X 的版本中已經(jīng)沒有 cmp 函數(shù),如果你需要實現(xiàn)比較功能,需要引入 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');True3.0 版本開始沒這個函數(shù)了,官方文檔是這么寫的:
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).)
新聞熱點
疑難解答