我有我写的一小段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
一定是真的。 - 这消除了在检查"
elif tx_avt < 100 and tx_avt >= 50:
"中做"tx_avt < 100
"部分的需要。
同样的逻辑向下级联并适用于其余elif
情况。
相关阅读:为什么 Python 没有开关语句及其替代方案。
您不需要 elifs 上的上限,因为这些上限由它们上面的子句解决......
elif tx_avt >= 50 : #do something
elif tx_avt >= 25 : #somthing else
在 Python 中的旁注中,您可以这样做
if 3 < ab < 10 : #check if ab is between 3 and 10
如果你的if-elif-else链变得很长,你可以使用这种方法:
for amt, tx in [(100, 1), (50, 2), (25, 3), (12.5, 4)]:
if tx_avt >= amt:
break
else:
tx = 5
注意:for
循环的 else
子句在未遇到break
时执行。 在这种情况下,它用于提供默认情况。
为了给出另一个想法,这可以使用 bisect 模块中的二叉搜索函数在一行中完成。
In [106]: def index(a,x):
.....: return len(a) - bisect.bisect_right(a, x) + 1
.....:
In [107]: a=[12.5,25,50,100]
In [108]: index(a,15)
Out[108]: 4
In [109]: index(a,25)
Out[109]: 3
In [110]: index(a,35)
Out[110]: 3
In [111]: index(a,50)
Out[111]: 2
In [112]: index(a,100)
Out[112]: 1
另一个基于[12.5, 25, 50, 100]是一个系列的想法:
MAX_BOUNDARY = 5
for tx, boundary in [(n, 25 * 2**(-n+3)) for n in range(1, MAX_BOUNDARY)]:
if tx_avt >= boundary:
break
else:
tx = MAX_BOUNDARY
(这是@StevenRumbalski版本略有修改)
这可以与@WaiYipTung关于 O(log(n)) 搜索bisect
的想法相结合,如果tx_avt的分布是均匀的(w.r.t. 系列函数),并且您的列表变得非常大。
否则,您应该坚持使用更简单,更容易理解的解决方案,例如建议的@JoranBeasley和@SampsonChen。