How to use cmp() in Python 3?

后端 未结 5 1483
甜味超标
甜味超标 2020-12-01 09:18

I cannot get the command cmp() to work.

Here is the code:

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

I am getting

相关标签:
5条回答
  • 2020-12-01 09:34

    When the sign is needed, probably safest alternative is using math.copysign:

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

    In particular if ang is of np.float64 type because of depreciation of the '-' operator. Example:

    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.
    

    instead one could use:

    def cmp_0(a, b):
        return bool(a > b) - bool(a < b)
    
    ang = np.float64(-2)
    cmp(ang, 0)
    # Result: -1
    
    0 讨论(0)
  • 2020-12-01 09:35

    In Python 3.x you can import operator and use operator module's eq(), lt(), etc... instead of cmp()

    0 讨论(0)
  • 2020-12-01 09:36

    adding to @maxin's answer, in python 3.x, if you want to compare two lists of tuples a and 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 讨论(0)
  • 2020-12-01 09:42

    If a or b is a class object, then the above answers will have the compilation error as below: For example: a is Class Clock: File "01_ClockClass_lab16.py", line 14, in cmp return (a > b) - (a < b) TypeError: '>' not supported between instances of 'Clock' and 'Clock'

    Change the type with int() to remove the error:

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

    0 讨论(0)
  • 2020-12-01 09:55

    As mentioned in the comments, cmp doesn't exist in Python 3. If you really want it, you could define it yourself:

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

    which is taken from the original What's New In Python 3.0. It's pretty rare -- though not unheard of -- that it's really needed, though, so you might want to think about whether it's actually the best way to do whatever it is you're up to.

    0 讨论(0)
提交回复
热议问题