我最近了解到,「%」符號用於計算Python中整數的其餘部分。但是我無法確定是否有另一個運算符或方法來計算Python中的百分比。就像「/」會給你一個商數,如果你只是使用一個浮點數作爲其中一個整數,它實際上會給你像傳統分區一樣的答案。那麼任何百分比方法?是否有運算符來計算Python中的百分比?
回答
你可以只將您兩個數字,由100注繁殖,如果「整」爲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
布賴恩的答案(自定義函數)是正確和最簡單的事情一般來說。
但是如果你確實想要用(非標準)'%'操作符來定義數字類型,就像桌面計算器一樣,所以'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的混合物用普通的整數或浮點數。
什麼也這段代碼繁瑣的你還必須形成一個整體或Real的所有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__")
真正先進的東西,雖然在這種情況下不是一個好主意,但它展示了Python類型的真正力量! – andychase
爲什麼我愛蟒蛇,這是什麼原因。另外,是否可以通過克隆* class *現有的'int'類型,設置'__mod__'和'__mul__'運算符,然後將其指定爲MyNumberClasswithPct?來重新定義所有抽象方法。 – ThorSummoner
如果我這樣做的話,上帝會生氣 – Pitto
我覺得問題解決了......在任何情況下,我認爲這個解決方案
def percent(string="500*22%"):
if "%" == string[-1] and "*" in string:
getnum = string[:-1]
ops = getnum.split("*")
result = int(ops[0]) * int(ops[1])/100
print("The {}% of {} is {}".format(ops[1], ops[0], result))
return result
else:
print("The argument must be a string like '500*22%'")
percent("1200*30%")
[輸出]:
1200的30%是360.0
- 1. Python百分比計算器
- 2. 計算百分比
- 3. 計算百分比
- 4. 計算百分比
- 5. 計算百分比
- 6. 計算百分比
- 7. 計算百分比
- 8. 在SQL中計算運行百分比
- 9. 計算百分比SQLite中
- 10. 計算百分比總計
- 11. Python的熊貓百分比計算
- 12. 計算python字典的百分比
- 13. 計算百分比的
- 14. 計算VB.NET的百分比
- 15. 計算豬的百分比
- 16. 計算百分比BigDecimals的
- 17. 在運行時計算百分比
- 18. MYSQL觸發器來計算百分比
- 19. PortgreSQL - 函數來計算百分比
- 20. 卡住來計算百分比
- 21. 計算百分比差異python
- 22. Python編程幫助(計算百分比)
- 23. 基於python字典計算百分比
- 24. 是否有任何內置函數來計算在SQL Server中的百分比
- 25. 百分比計算與行
- 26. Tableau百分比計算
- 27. SSRS - 計算百分比
- 28. 計算百分比錯誤
- 29. TSQL計算百分比
- 30. 用PHP計算百分比
要說清楚,你的意思是'x * y/100.0'還是'(x/y)* 100.0'?我們大多數人把它看作乘法;布賴恩把它看作分裂。 – smci