如何在Python 3中使用cmp()?

问题描述 投票:0回答:9

我无法让命令

cmp()
在 Python 3 中工作。

这是代码:

a = [1,2,3]
b = [1,2,3]
c = cmp(a,b)
print (c)

我收到错误:

Traceback (most recent call last):
  File "G:\Dropbox\Code\a = [1,2,3]", line 3, in <module>
    c = cmp(a,b)
 NameError: name 'cmp' is not defined
python python-3.x comparison-operators
9个回答
105
投票

正如评论中提到的,

cmp
在Python 3中不存在。如果你真的想要它,你可以自己定义它:

def cmp(a, b):
    return (a > b) - (a < b) 

摘自原文Python 3.0 的新增功能。不过,确实需要它的情况非常罕见(尽管并非闻所未闻),因此您可能需要考虑一下它是否实际上是完成您要做的事情的最佳方式。


13
投票

在 Python 3.x 中,您可以

import operator
并使用运算符模块的
eq()
lt()
等...而不是
cmp()


1
投票

当需要符号时,最安全的选择可能是使用 math.copysign:

import math
ang = -2
# alternative for cmp(ang, 0):
math.copysign(1, ang)

# Result: -1

特别是如果 ang 是 np.float64 类型,因为“-”运算符已被弃用。 示例:

import numpy as np

def cmp_0(a, b):
    return (a > b) - (a < b)

ang = np.float64(-2)
cmp_0(ang, 0)

# Result:
# DeprecationWarning: numpy boolean subtract, the `-` operator, is deprecated, 
# use the bitwise_xor, the `^` operator, or the logical_xor function instead.

相反,人们可以使用:

def cmp_0(a, b):
    return bool(a > b) - bool(a < b)

ang = np.float64(-2)
cmp(ang, 0)
# Result: -1

0
投票

添加@maxin的答案,在

python 3.x
中,如果你想比较两个元组列表
a
b

import operator

a = [(1,2),(3,4)]
b = [(3,4),(1,2)]
# convert both lists to sets before calling the eq function
print(operator.eq(set(a),set(b))) #True

0
投票

在一般情况下,这些都是

cmp()
的良好替代品,对于原始海报给出的实际用例,当然

a = [1,2,3]
b = [1,2,3]
c = a != b
print(c)

或者只是

a = [1,2,3]
b = [1,2,3]
print(a != b)

效果会很好。


0
投票

你可以使用这个更简单的方法

a=[1,2,3]
b=[1,2,3]
c=not(a!=b)
c
True

-1
投票

如果a或b是类对象, 那么上面的答案将会出现编译错误,如下所示: 例如:a是班级时钟:

  File "01_ClockClass_lab16.py", line 14, in cmp
    return (a > b) - (a < b)
TypeError: '>' not supported between instances of 'Clock' and 'Clock'

用 int() 更改类型以消除错误:

def cmp(a, b):
    return (int(a) > int(b)) - (int(a) < int(b))  

-2
投票

一种简单的方法是使用

a - b
并检查标志。

def cmp(a, b):
    return a - b
if a < b, negative

if a = b, zero

if a > b, positive

-4
投票

这个

cmp()
函数仅适用于Python 2.x版本,如果你尝试在3.x版本中使用它会给出错误:

NameError: name 'cmp' is not defined
[Finished in 0.1s with exit code 1]

请看下面的代码:

a=60
b=90
print(cmp(a,b))

输出:

-1

比较整数时 cmp() 只是执行其参数的减法,即在本例中为 a-b,如果减法为 -ve,则返回 -1,即 ab

a=90
b=60
print(cmp(a,b))

输出:

1

再次:

a="abc"
b="abc"
print(cmp(a,b))

输出:

0

当两个参数相等时,即 a=b,它返回 0 作为输出。在这里,我们传递了两个字符串类型的值。这里,cmp() 逐个字符地比较两个字符串,如果发现相同则返回 0。

© www.soinside.com 2019 - 2024. All rights reserved.