![](/img/trans.png)
[英]Is there a more Pythonic way to combine an Else: statement and an Except:?
[英]Combine multiple if else statement
我做了一個功能,如果商品的價值增加 1%,閾值也會增加 1%。 這里最好的情況是在 python 中使用 switch 語句。但是 python 中沒有,如 Python 中switch 語句的替換?
因此,我在 python 中使用了多個 if else 和 elif 語句。
代碼:
price = 100.0
Price=104
threshold=90.0
if Price == 1.01*price:
threshold=1.01*threshold
elif Price == 1.02*price:
threshold=1.02*threshold
elif Price==1.03*price:
threshold=1.03*threshold
else:
threshold=1.04*threshold
這里:
價格 = 商品初始價格
價格=我們購買數量后的價格。 每分鍾不斷變化
閾值 = 商品可以達到的最低價格。 如果商品價格低於此閾值,我們將出售商品。
通過實施此功能我的意思是,商品價格的單位百分比增加應該使閾值增加相同的單位百分比。如果商品價格低於原始購買價格,則不應對閾值進行任何操作。
因此,當商品價格達到 101,即商品價格上漲 1% 時,閾值也會增加相同的數量。 如果商品價格增加到 2%,則閾值也增加原始閾值的 2% 90 增加 2% 是 91.8 如果購買價格下降 1%,即變為 99,則閾值保持不變,即 90。如果價格繼續減少並低於我們銷售商品的門檻。
現在
因此,我通過上述程序得到的 output 是:
price Price Threshold
100 101 90.9
100 102 91.8
100 103 92.7
100 104 93.6
100. 99. 90
100. 96 90
100. 91. 90
請注意,這只是一個示例。 在真實場景中,價格值每 1 秒更新一次
我的問題是我在程序中使用了多個 if 和 elif 語句。 那么有沒有辦法將這些多個if和elif語句組合起來,讓代碼更短,覆蓋所有場景呢?
如果你不介意升級你的 pyhon,在 python 3.10 中他們已經合並了 switch-case 模式匹配。 https://docs.python.org/3.10/whatsnew/3.10.html
但是,我會為此使用循環並為此目的使用更抽象的編碼。
if Price == (1+increase)*price:
threshold = (1+increase)*price
其中 increase 是您要添加到價格中的百分比。 鑒於該增加,您可以檢查價格何時上漲到該增量並更新閾值。
另一種方法是
increase= Price/price
但是,我還沒有測試過,所以試一試; ;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.