Python中List cmp()知识点有哪些

发布时间:2021-08-12 13:55:30 作者:小新
来源:亿速云 阅读:150

小编给大家分享一下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).)

以上是“Python中List cmp()知识点有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. PyCharm入门教程——PyCharm编辑器
  2. 关键字驱动模式 实现登录qq邮箱并发送邮件的自动化测试

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python list

上一篇:python中语法定义的示例分析

下一篇:Ajax怎么实现点击不断加载数据列表

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》