[英]How can I shortern if, elif, elif statements in Python
我怎样才能使下面的代码简短:
q=0.34
density=''
if abs(q) ==0:
density='Null'
elif abs(q) <= 0.09:
density='negligible'
elif abs(q) <= 0.49:
density='slight'
elif abs(q) <= 0.69:
density='strong'
else:
density='very strong'
print(q,", ", density)
预期输出:
0.34, 'slight'
我认为有一个使用dictionaries
的解决方案,
非常感谢您的帮助!
你可以尝试这样的事情:
def f(q):
# List of your limits values and their density values
values = [(0, "Null"), (0.09, "negligible"), (0.49, "slight"), (0.69, "strong")]
# Default value of the density, i.e. your else statement
density = "very strong"
# Search the good density and stop when it is found
for (l, d) in values:
if abs(q) <= l:
density = d
break
print(q, ", ", density)
我认为注释足够明确,可以解释代码,但如果不清楚,请毫不犹豫地询问。
在这里编写了一个解决方案,它不是检查所有 if-else 语句,而是循环遍历一组值并找到输入值所属的空间:
import numpy as np
vals = [0, 0.09,0.49,0.69,]
msgs = ['Null', 'negligible', 'slight', 'strong', 'very strong']
q=0.5
density=''
def calc_density(q:float) -> str:
are_greater_than = q>np.array(vals)
if all(are_greater_than): bools = -1
else: bools = np.argmin(are_greater_than)
return msgs[bools]
for q in [-0.1, 0.0, 0.2, 0.07, 0.8]:
print(q, calc_density(q))
# >>> -0.1 Null
# >>> 0.0 Null
# >>> 0.2 slight
# >>> 0.07 negligible
# >>> 0.8 very strong
希望这可以帮助!
如果在单个地方使用这个,这段代码就这样好了,没有什么问题。
如果有更多的地方你想为一个字符串分配一个数字范围,你可以使用一个函数或一个类来做,以一种你可以更好地编码值的方式。
例如,一个简单的、可配置的函数来做同样的事情是:
def _range_to_str(ranges, value):
for threshold, description in ranges.items():
if value <= threshold:
return description
raise ValueError(f"{value} out of range for {ranges}")
densities = {0: "", 0.09:"negligible", 0.49: "slight", ...}
def density_description(value):
return _range_to_str(densities, value)
q=0.34
density=''
conditions = [
(0,'null'),
(0.09, 'negligible'),
(0.49, 'slight'),
(0.69, 'strong')
]
# loops through the conditions and check if they are smaller
# if they are, immediately exit the loop, retaining the correct density value
for limit, density in conditions:
if q <= limit:
break
# this if statement checks if its larger than the last condition
# this ensures that even if it never reached any condition, it doesn't
# just output the last value
if q > conditions[-1][0]:
density = 'very strong'
print(q,", ", density)
当然如果你想让它更短:)(假设 q 总是小于 9999)
q=0.34
c = [(0,'null'),(0.09,'negligible'),(0.49,'slight'),(0.69,'strong'), (9999,'very strong')]
print(q,',',[j for i,j in c if abs(q)<=i][0])
编辑:修复了 Khaled DELLAL 指出的答案中的错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.