Why doesn't Python have a sign function?

前端 未结 12 707
旧巷少年郎
旧巷少年郎 2020-12-02 04:54

I can\'t understand why Python doesn\'t have a sign function. It has an abs builtin (which I consider sign\'s sister), but no si

12条回答
  •  借酒劲吻你
    2020-12-02 05:05

    numpy has a sign function, and gives you a bonus of other functions as well. So:

    import numpy as np
    x = np.sign(y)
    

    Just be careful that the result is a numpy.float64:

    >>> type(np.sign(1.0))
    
    

    For things like json, this matters, as json does not know how to serialize numpy.float64 types. In that case, you could do:

    float(np.sign(y))
    

    to get a regular float.

提交回复
热议问题