在python中,在字典中使用多变量最有效的方法是什么?

2024-10-03 09:10:36 发布

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

这是我的代码,我在寻找,是另一种最有效的编码方式吗? 我有多个变量,并插入字典。 请感觉到建议和其他选项,如阵列等将做

def momentEndSpan(span_type,max_combo,length):
    if "simply supported" == span_type:
        q = max_combo
        force = {}
        RA = {"PA" : q*length/2}
        RB = {"PB" : q*length/2}
        RA_moment = {"MA" : 0}
        R_mid_moment = {"Mmid": (q*math.pow(length,2))/8 }
        RB_moment = { "MB" : 0}
        force.update(RA)
        force.update(RB)
        force.update(RA_moment)
        force.update(R_mid_moment)
        force.update(RB_moment)
        return force
    elif "one end continuous" == span_type:
        q = max_combo
        x = (3/8)*length
        force = {}
        RA = {"Phinge" : 3*q*length/8}
        RB = {"Pfixed" : 5*q*length/8}
        RA_moment = {"Mhinge" : 0}
        R_mid_moment = {"Mmid": (q*math.pow(length,2))*(9/128) }
        RB_moment = { "MB" : -1*(q*math.pow(length,2))/8 }
        force.update(RA)
        force.update(RB)
        force.update(RA_moment)
        force.update(R_mid_moment)
        force.update(RB_moment)
        return force        

非常感谢


Tags: typeupdatemathmblengthmaxraspan
1条回答
网友
1楼 · 发布于 2024-10-03 09:10:36

“更Pythonic”的方法是创建一个字典并更新一次

q = max_combo
force = {} 

if "simply supported" == span_type:
    new = {"PA" : q*length/2,
           "PB" : q*length/2,
           "MA" : 0, "Mmid": (q*math.pow(length,2))/8,
           "MB" : 0}

elif "one end continuous" == span_type:
        x = (3/8)*length
        new = {"Phinge" : 3*q*length/8,
               "Pfixed" : 5*q*length/8,
               "Mhinge" : 0,
               "Mmid": (q*math.pow(length,2))*(9/128),
               "MB" : -1*(q*math.pow(length,2))/8 }

force.update(new)

另外,请注意,如果force字典不包含任何先前定义的项,则只需返回new和/或在下一个操作中继续更新new(如果有)。或者只使用名称force而不是new

q = max_combo

if "simply supported" == span_type:
    force = {...}

elif "one end continuous" == span_type:
        x = (3/8)*length
        force = {...}

相关问题 更多 >