2017-06-20 39 views
0

我想讓代碼更緊湊。我認爲有一部分可以很好地減少,但不知道如何去做。我在下面複製的代碼中添加註釋,以便快速找到它。如何合成這個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) 

任何幫助將是一件好事。

+0

我想你想在不在tex.stackexchange中的計算器。如果gnorm是None:''None'比較 – percusse

+1

'gnorm =「」if gnorm is None else「gnorm =」+ str(gnorm)' – percusse

+0

@percusse是的,我很抱歉 – HernanProust

回答

1

我清理和糾正在這裏你的代碼:

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 "" 

這是怎麼寫你的方法的簡寫。此外,你永遠不應該評估一個布爾值==爲真,布爾本身就是條件。你也是或不是不等於評價。

+0

謝謝,它有幫助。但那不完全是我問的。我重新說明:是否有一種方法可以將所有'if'和'不是None'都放置一次?由於gnorm,週期和eps行類似。 – HernanProust

+0

考慮到它們是單獨變量進行單獨評估,將它們全部壓縮爲一件事情沒有意義。如果你想讓它看起來不那麼混亂,你可以創建一個方法來發送變量,然後進行評估,但考慮到它是一行代碼,我不會建議它。 – JoshKopen

+0

我明白了,好.. – HernanProust

相關問題