描述
cmp() 方法用于比較兩個(gè)列表的元素。
語(yǔ)法
cmp()方法語(yǔ)法:
cmp(list1, list2)
參數(shù)
list1 -- 比較的列表。
list2 -- 比較的列表。
返回值
如果比較的元素是同類型的,則比較其值,返回結(jié)果。
如果兩個(gè)元素不是同一種類型,則檢查它們是否是數(shù)字。
- 如果是數(shù)字,執(zhí)行必要的數(shù)字強(qiáng)制類型轉(zhuǎn)換,然后比較。
- 如果有一方的元素是數(shù)字,則另一方的元素"大"(數(shù)字是"最小的")
- 否則,通過類型名字的字母順序進(jìn)行比較。
如果有一個(gè)列表首先到達(dá)末尾,則另一個(gè)長(zhǎng)一點(diǎn)的列表"大"。
如果我們用盡了兩個(gè)列表的元素而且所 有元素都是相等的,那么結(jié)果就是個(gè)平局,就是說返回一個(gè) 0。
實(shí)例
以下實(shí)例展示了 cmp()函數(shù)的使用方法:
#!/usr/bin/python list1, list2 = [123, 'xyz'], [456, 'abc'] print cmp(list1, list2); print cmp(list2, list1); list3 = list2 + [786]; print cmp(list2, list3)
以上實(shí)例輸出結(jié)果如下:
-1
1
-1
Python 3.X 的版本中已經(jīng)沒有 cmp 函數(shù),如果你需要實(shí)現(xiàn)比較功能,需要引入 operator 模塊,適合任何對(duì)象,包含的方法有:
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)
實(shí)例
>>> import operator >>> operator.eq('hello', 'name'); False >>> operator.eq('hello', 'hello'); True
3.0 版本開始沒這個(gè)函數(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).)
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
