简体   繁体   English

Python中是否有算子计算百分比?

[英]Is there an operator to calculate percentage in Python?

I've recently learned that the " % " sign is used to calculate the remainder of an integer in Python.我最近了解到,“%”符号用于计算 Python 中 integer 的余数。 However I was unable to determine if there's another operator or method to calculate percent in Python.但是我无法确定 Python 中是否有其他运算符或方法来计算百分比。

Like with " / " which will give you the quotient, if you just use a float for one of the integers, it will actually give you the answer like traditional division.就像“/”会给你商数一样,如果你只是对其中一个整数使用浮点数,它实际上会给你像传统除法一样的答案。 So is there a method to work out percentage?那么有没有办法计算百分比呢?

You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:您可以将两个数字相除并乘以 100。请注意,如果“整数”为 0,这将引发错误,因为询问数字是 0 的百分比是没有意义的:

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

Or with a % at the end:或者以 % 结尾:

 def percentage(part, whole):
  Percentage = 100 * float(part)/float(whole)
  return str(Percentage) + “%”

Or if the question you wanted it to answer was "what is 5% of 20", rather than "what percentage is 5 of 20" (a different interpretation of the question inspired by Carl Smith's answer ), you would write:或者,如果您希望它回答的问题是“20 的 5% 是多少”,而不是“20 的 5 的百分比是多少”(受Carl Smith 的回答启发的对问题的不同解释),您可以这样写:

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

There is no such operator in Python, but it is trivial to implement on your own. Python 中没有这样的操作符,但是自己实现很简单。 In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one.在计算实践中,百分比几乎没有模那么有用,所以我能想到的语言都没有实现。

use of %用于 %

def percent(expression):
    if "%" in expression:
        expression = expression.replace("%","/100")
    return eval(expression)

>>> percent("1500*20%")
300.0

Somthing simple简单的东西

>>> p = lambda x: x/100
>>> p(20)
0.2
>>> 100*p(20)
20.0
>>>

Brian's answer (a custom function) is the correct and simplest thing to do in general. Brian 的答案(自定义函数)通常是正确且最简单的方法。

But if you really wanted to define a numeric type with a (non-standard) '%' operator, like desk calculators do, so that 'X % Y' means X * Y / 100.0, then from Python 2.6 onwards you can redefine the mod () operator :但是,如果你真的想定义一个数字类型有(非标)“%”经营者,像台计算器做,让“X%Y”手段X * Y / 100.0,然后在Python 2.6起,可以重新定义mod () 运算符

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)
    #...

This could be dangerous if you ever use the '%' operator across a mixture of MyNumberClasswithPct with ordinary integers or floats.如果您曾经在 MyNumberClasswithPct 与普通整数或浮点数的混合中使用 '%' 运算符,这可能是危险的。

What's also tedious about this code is you also have to define all the 21 other methods of an Integral or Real, to avoid the following annoying and obscure TypeError when you instantiate it这段代码的乏味之处还在于,您还必须定义 Integral 或 Real 的所有其他 21 种方法,以避免在实例化它时出现以下烦人且晦涩的 TypeError

("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__")

Very quickly and sortly-code implementation by using the lambda operator.使用lambda运算符非常快速且有序地实现代码。

In [17]: percent = lambda part, whole:float(whole) / 100 * float(part)
In [18]: percent(5,400)
Out[18]: 20.0
In [19]: percent(5,435)
Out[19]: 21.75
def percent(part, whole):
    try:
        return 100 * float(part) / float(whole)
    except ZeroDivisionError:
        return 0

I have found that the most useful case for me is to compute the calculations as ratios and then printing the results formatting them as percentages thanks to Python formatting options :我发现对我来说最有用的情况是将计算计算为比率,然后使用 Python 格式化选项将结果格式化为百分比:

result = 1.0/2.0            # result is 0.5
print(f'{result:.0%}')      # prints "50%"

Just use this就用这个

score_in_percentage = round( score *100 , 2 )
print(f' {score_in_percentage}% ') #50%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM