簡體   English   中英

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

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

我最近了解到,“%”符號用於計算 Python 中 integer 的余數。 但是我無法確定 Python 中是否有其他運算符或方法來計算百分比。

就像“/”會給你商數一樣,如果你只是對其中一個整數使用浮點數,它實際上會給你像傳統除法一樣的答案。 那么有沒有辦法計算百分比呢?

您可以將兩個數字相除並乘以 100。請注意,如果“整數”為 0,這將引發錯誤,因為詢問數字是 0 的百分比是沒有意義的:

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

或者以 % 結尾:

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

或者,如果您希望它回答的問題是“20 的 5% 是多少”,而不是“20 的 5 的百分比是多少”(受Carl Smith 的回答啟發的對問題的不同解釋),您可以這樣寫:

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

Python 中沒有這樣的操作符,但是自己實現很簡單。 在計算實踐中,百分比幾乎沒有模那么有用,所以我能想到的語言都沒有實現。

用於 %

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

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

簡單的東西

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

Brian 的答案(自定義函數)通常是正確且最簡單的方法。

但是,如果你真的想定義一個數字類型有(非標)“%”經營者,像台計算器做,讓“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)
    #...

如果您曾經在 MyNumberClasswithPct 與普通整數或浮點數的混合中使用 '%' 運算符,這可能是危險的。

這段代碼的乏味之處還在於,您還必須定義 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__")

使用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

我發現對我來說最有用的情況是將計算計算為比率,然后使用 Python 格式化選項將結果格式化為百分比:

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

就用這個

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