如何缩短Python中的if、elif、elif语句

q9rjltbz  于 2022-12-25  发布在  Python
关注(0)|答案(4)|浏览(187)

我怎样才能使下面的代码更短:

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有一个解决方案,
任何来自你方的帮助将不胜感激!

qjp7pelc

qjp7pelc1#

你可以试试这样的方法:

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)

我认为注解已经足够清楚地解释了代码,但是如果不清楚,请不要犹豫。

toe95027

toe950272#

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指出的答案错误

uyhoqukh

uyhoqukh3#

这里编写了一个解决方案,它不是检查所有的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

希望这有帮助!

brccelvz

brccelvz4#

如果只在一个地方使用它,那么这段代码就很好,没有任何问题。
如果有更多的地方需要为字符串指定数值范围,可以使用函数或类来完成,这样可以更好地对值进行编码。
例如,一个简单的、可配置的函数可以完成同样的任务:

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)

相关问题