Python List cmp()知识点总结

yipeiwu_com5年前Python基础

描述

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中字符串数组逆序排列方法总结

python中字符串数组如何逆序排列?下面给大家介绍几种方法: 1、数组倒序: 原始元素的倒序排列 (1)切片 >>> arr = [1,2,3,4,3,4]>...

python使用xlrd与xlwt对excel的读写和格式设定

前言 python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。本文主要介绍了python使用xlrd与xlwt对excel的读...

python中bytes和str类型的区别

经过一上午的查找资料。大概理清楚了bytes类型和str类型的区别。 bytes类型和str类型在呈现形式有相同之处,如果你print一个bytes类型的变量,会打印一个用b开头,用单引...

python类的方法属性与方法属性的动态绑定代码详解

动态语言与静态语言有很多不同,最大的特性之一就是可以实现动态的对类和实例进行修改,在Python中,我们创建了一个类后可以对实例和类绑定心的方法或者属性,实现动态绑定。 最近在学习pyt...

在Pycharm中将pyinstaller加入External Tools的方法

在Pycharm中将pyinstaller加入External Tools的方法

Pycharm: 2017.1.2 PyInstaller: 3.3.1 第一步:安装pyinstaller 网上有很多种方法,在此不赘述。pycharm中,安装很方便。 进入设置(co...