如何合成这个python函数

2024-10-03 23:30:59 发布

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

我正在努力使代码更紧凑。我认为有一部分可以很好地减少,但不知道如何做到这一点。我在下面复制的代码中添加了一条注释,以便您快速找到它。你知道吗

下一个代码是:

def change_to_mop_gen(infile, namedir="",charge=0, gnorm=None, separate=True, hamiltonian="PM6", calctype="opt", multiplicity="singlet", eps=None, cycles=None):
#armado de la salida
    if calctype=="thermo(298,298,0)":
        calctype1="thermo"
    else: 
        calctype1=calctype
    outfile=infile.split(".")[0] + "-" + calctype1 + "-" + hamiltonian

#~ here comes the set of if / else sentences i think could be reduced

    if gnorm !=None:
        gnorm="gnorm=" + str(gnorm)
    else:
        gnorm= " "
    if cycles!=None:
        cycles="cycles="+str(cycles)
    else:
        cycles=""
    if separate==True:
        outfile=outfile + "_*.mop"
    else:
        outfile=outfile + ".mop"
    if eps !=None:
        eps="eps=" + str(eps)
    else:
        eps = ""  

    #~here it ends

    keywords = "-xk '%s  %s %s %s %s %s charge=%i'"%(cycles, hamiltonian, calctype, multiplicity, eps, gnorm, charge)
    #change directory of outfile
    if namedir!="":
        outfile= namedir + "/" + outfile
    return change_format(infile,outfile, keywords)

任何帮助都是好的。你知道吗


Tags: 代码noneifepschangeelseinfileoutfile
1条回答
网友
1楼 · 发布于 2024-10-03 23:30:59

我在这里清理并更正了您的代码:

gnorm= ("gnorm=" + str(gnorm)) if gnorm is not None else ""
cycles="cycles="+str(cycles) if cycles is not None else ""
outfile=(outfile + "_*.mop") if separate else (outfile + ".mop")
eps=("eps=" + str(eps)) if eps is not None else ""

这是如何写你的方法速记。另外,您不应该将布尔值==计算为真,布尔值本身就是条件。你做的是或不是都不等于评估。你知道吗

相关问题 更多 >