將事情分解成若干步驟是解決問題的好方法(以後總是可以重新組合步驟),而且有80%的解決方法。
您已經有positive
和negative
列表。所以,你需要每一個成一個字符串轉換,那麼就:
print poshalf, "=", neghalf
那麼,你如何轉換成positive
poshalf
?那麼,它的每一個成員,由'+'
分離的表示,所以如果你有一個功能stringify
,可以將每個成員納入其表示,這只是:
poshalf = '+'.join(stringify(el, mul) for (el, mul) in pos)
neghalf = '+'.join(stringify(el, mul)[1:] for (el, mul) in neg)
的[1:]
有取出-
跡象。如果mul
實際上是一個整數,而不是字符串,它可能是有意義的它傳遞給stringify
之前剛剛否定值:
neghalf = '+'.join(stringify(el, -mul) for (el, mul) in neg)
現在,這是什麼「字符串」的功能是什麼樣子?那麼,每個成員是一對(el, mul)
。如果他們都是字符串,你可以添加它們。從以前的問題,mul
最終可能是在這一點上某種數量的,但是這是幾乎一樣簡單:
def stringify(el, mul):
return str(mul) + el
把它放在一起,就大功告成了。如果你從來沒有使用(el, mul)
用於任何其他目的除了呼籲它stringify
,只需調用stringify
擺在首位,並將結果:
def balance_equation(species,coeff):
data=zip(coeff,species)
positive=[]
negative=[]
for (mul,el) in data:
if int(mul)<0:
negative.append(str(mul)[1:] + el)
if int(mul)>0:
positive.append(str(mul) + el)
return positive, negative
請記住,使這一切更簡單
的一種方式最後一行,你已經放棄了你以前的問題和這個問題的兩個版本!如果你永遠不會返回這些值,那麼找出它們的所有努力都會被浪費掉,並且調用者只是獲得None
作爲答案。
顯然無論是str
還是int
是不必要的,但爲了安全起見,你應該看看你周圍的代碼,並刪除不必要的代碼。 (如果你正在服用mul
爲int,你可能想str(-mul)
,而不是str(mul)[1:]
,如前所述。)
一旦你得到了這個,如果你瞭解列表解析,你可能會意識到,這是一個熟悉的模式:從[]
開始,循環一些其他集合,並且每個值都滿足一些測試。換句話說:
def balance_equation(species,coeff):
data=zip(coeff,species)
positive = [str(mul) + el for (mul, el) in data if int(mul) > 0]
negative = [str(mul) + el for (mul, el) in data if int(mul) < 0]
return positive, negative
您可能注意到,您可以簡化這一更進一步,只使用名單是建立琴絃的東西,所以你也許只想返回一個字符串方程函數(以在這種情況下,您可以使用生成器表達式而不是列表理解 - 如果您還不瞭解它們,請忽略該部分)。
def balance_equation(species,coeff):
data=zip(coeff,species)
positive = '+'.join(str(mul) + el for (mul, el) in data if int(mul) > 0)
negative = '-'.join(str(mul) + el for (mul, el) in data if int(mul) < 0)
return positive + '=' + negative
當然現在你返回一個字符串,而不是一對名單的,所以你必須要改變的組合名單,只是print balance_equation(species, coeff)
而不是調用代碼。
最後一件事:您似乎在每次調用時都會顛倒係數/乘數和物種/元素的順序。例如:
def balance_equation(species,coeff):
data=zip(coeff,species)
除非有很好的理由不這樣做,最好挑一個秩序和一致貫穿始終,或者你總是要運行到哪裏,你讓他們倒退的錯誤。
你的意思是'1H2O + 3O2 = 4CO2'? – irrelephant
是的,謝謝,我會修復現在寫 – user1819717