= 100: tx = 1 elif tx_avt-6ren">
gpt4 book ai didi

python - 有没有更好的方法来编写这个 "if" bool 值评估?

转载 作者:太空狗 更新时间:2023-10-29 17:35:42 25 4
gpt4 key购买 nike

我有一小段我写的 python 代码。它有效,但我认为应该有一种更简化的方法来实现相同的结果。我只是没有看到它。有什么想法吗?

if tx_avt >= 100: tx = 1 
elif tx_avt < 100 and tx_avt >= 50: tx = 2
elif tx_avt < 50 and tx_avt >= 25: tx = 3
elif tx_avt < 25 and tx_avt >= 12.5: tx = 4
else: tx = 5

最佳答案

您可以将其更改为:

if tx_avt >= 100: tx = 1 
elif tx_avt >= 50: tx = 2
elif tx_avt >= 25: tx = 3
elif tx_avt >= 12.5: tx = 4
else: tx = 5

解释:

  • 如果if tx_avt >= 100不是真的,那么你可以推断出tx_avt < 100 必须为真。
  • 这消除了在检查“tx_avt < 100”中执行“elif tx_avt < 100 and tx_avt >= 50:”部分的需要。

相同的逻辑向下级联并适用于 elif 的其余部分例。


相关阅读:Why Python Doesn't Have a Switch Statement, and its Alternatives .

关于python - 有没有更好的方法来编写这个 "if" bool 值评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13589811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com