在Python中有计算百分比的运算符吗?

2024-04-20 05:02:12 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

你可以把你的两个数字除以100。注意,如果“whole”为0,这将抛出一个错误,因为询问数字0的百分比是没有意义的:

def percentage(part, whole):
  return 100 * float(part)/float(whole)

或者,如果你想让它回答的问题是“20的5%是什么”,而不是“20的5%是什么”(对这个问题的另一种解释受到Carl Smith's answer的启发),你可以这样写:

def percentage(percent, whole):
  return (percent * whole) / 100.0

在Python中没有这样的操作符,但是单独实现是很简单的。在计算实践中,百分比并没有模块那么有用,所以没有一种语言可以实现它。

Brian的答案(一个自定义函数)通常是正确和最简单的。

但是如果你真的想用一个(非标准的)“%”操作符来定义一个数值类型,就像桌面计算器一样,那么'X%Y'意味着X*Y/100.0,那么从Python 2.6开始,你可以重新定义the mod() operator

import numbers

class MyNumberClasswithPct(numbers.Real):
    def __mod__(self,other):
        """Override the builtin % to give X * Y / 100.0 """
        return (self * other)/ 100.0
    # Gotta define the other 21 numeric methods...
    def __mul__(self,other):
        return self * other # ... which should invoke other.__rmul__(self)
    #...

如果在MyNumberClasswithPct与普通整数或浮点数的混合体中使用“%”运算符,则这可能是危险的。

这段代码的另一个乏味之处在于,您还必须定义一个整数或实数的所有21个其他方法,以避免在实例化它时出现以下恼人和晦涩的类型错误

("Can't instantiate abstract class MyNumberClasswithPct with abstract methods __abs__,  __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__, __mul__,  __neg__, __pos__, __pow__, __radd__, __rdiv__, __rfloordiv__, __rmod__, __rmul__,  __rpow__, __rtruediv__, __truediv__, __trunc__")

相关问题 更多 >