基于if语句解包元组

2024-09-24 12:21:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用基于if语句的元组中的值创建一个嵌套字典。代码中的变量(estabilidad_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

Tags: andinforifdevariableselifpor
1条回答
网友
1楼 · 发布于 2024-09-24 12:21:44

许多像这样的大型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_atm不是有效的键,这将引发KeyError,此时您可以选择捕获并执行一些合理的操作,而不是简单地让程序退出

相关问题 更多 >