Python 基于if语句解包元组

Python 基于if语句解包元组,python,dictionary,tuples,Python,Dictionary,Tuples,我正在使用基于if语句的元组中的值创建一个嵌套字典。CODESTABILIDAD_atm、Q_puntos_muestreo和puntos de muestreo中的变量在全局范围内定义。当我运行我得到的函数时,错误是:名称a未定义。我不知道为什么它不起作用。。。我曾想过申请namedtuple,但我不确定哪种方法是最好的。谢谢 variables_coeficientes_por_punto = {} for punto in puntos_de_muestreo: x = punt

我正在使用基于if语句的元组中的值创建一个嵌套字典。CODESTABILIDAD_atm、Q_puntos_muestreo和puntos de muestreo中的变量在全局范围内定义。当我运行我得到的函数时,错误是:名称a未定义。我不知道为什么它不起作用。。。我曾想过申请namedtuple,但我不确定哪种方法是最好的。谢谢

variables_coeficientes_por_punto = {}

for punto in puntos_de_muestreo:
    x = punto[0]
    if estabilidad_atm == 'A' and x <= 1:
        a,c,d,f = (213,440.8,1.941,9.27)
    elif estabilidad_atm == 'A' and x > 1:
        a,c,d,f = (213,459.7,2.094,-9.6)
    elif estabilidad_atm == 'B' and x <= 1:
        a,c,d,f = (156,106.6,1.149,3.3)
    elif estabilidad_atm == 'B' and x > 1:
        a,c,d,f = (156,108.2,1.098,2)
    elif estabilidad_atm == 'C' and x <= 1:
        a,c,d,f = (104,61,0.911,0)
    elif estabilidad_atm == 'C' and x > 1:
        a,c,d,f = (104,61,0.911,0)
    elif estabilidad_atm == 'D' and x <= 1:
        a,c,d,f = (68,33.2,0.725,-1.7)
    elif estabilidad_atm == 'D' and x > 1:
        a,c,d,f = (68,44.5,0.516,-13)
    elif estabilidad_atm == 'E' and x <= 1:
        a,c,d,f = (50.5,22.8,0.678,-1.3)
    elif estabilidad_atm == 'E' and x > 1:
        a,c,d,f = (50.5,55.4,0.305,-34)
    elif estabilidad_atm == 'F' and x <= 1:
        a,c,d,f = (34,14.35,0.740,-0.35)
    elif estabilidad_atm == 'F' and x > 1:
        a,c,d,f = (34,62.6,0.180,-48.6)
    for i in range(Q_puntos_muestreo):
        variables_coeficientes_por_punto['punto '+ str(i+1)] = {}
        variables_coeficientes_por_punto['punto ' + str(i+1)]['a'] = a
        variables_coeficientes_por_punto['punto ' + str(i+1)]['c'] = c
        variables_coeficientes_por_punto['punto ' + str(i+1)]['d'] = d
        variables_coeficientes_por_punto['punto ' + str(i+1)]['f'] = f
许多像这样的大型if语句可以用dict替换。例如

tuples = {
  'A': lambda x: (213,440.8,1.941,9.27) if x < 1 else (213,459.7,2.094,-9.6),
  'B': lambda x: (156,106.6,1.149,3.3) if x <= 1 else (156,108.2,1.098,2),
  ...
}

variables_coeficientes_por_punto = {}

for punto in puntos_de_muestreo:
    x = punto[0]
    try:
        a, c, d, f = tuples[estabilidad_atm](x)
    except KeyError:
        raise

    for i in range(1, Q_puntos_muestreo + 1):
        variables_coeficientes_por_punto['punto '+ str(i)] = dict(a=a, c=c, d=d, f=f)

如果estabilidad\u atm不是有效的密钥,这将引发一个KeyError,此时您可以选择捕获并执行一些合理的操作,而不是简单地让程序退出。

如果您的条件均未计算为True,则不会定义a。您应该在elifs链之后添加一个else:为a、c、d、f设置默认值,或者引发一个特定的错误。除了前面的注释中提到的缺少else块之外,这段代码没有问题,python中没有开关,所以一堆条件是合适的替代方法之一。无关。代替4个单独的赋值,您可以只赋值{'a','c','d','f':f}您可能还想嵌套您的条件:if estabilidad_atm='a':if x不确定它是否会更好。@OlvinRoght这是一种标准做法,实际上在任何有if Else阶梯的地方都会有很大的if Else阶梯。@BłażejMichalik,是的,但我不确定它是否是最有效的。@OlvinRoght相当确定我们并不是真的在寻找效率。由于代码可读性差,作者犯了一个错误。如果你想提高效率,你甚至可以考虑在C扩展中无分支地进行,但这肯定不会有助于可读性。@BłażejMichalik,ofc不是,但如果。。埃利夫。。其他方面则要明确得多。