到目前为止我所拥有的:
def balance_equation(species,coeff):
data=zip(coeff,species)
positive=[]
negative=[]
for (mul,el) in data:
if int(mul)<0:
negative.append((el,mul))
if int(mul)>0:
positive.append((el,mul))
Run Code Online (Sandbox Code Playgroud)
我知道这不会打印任何东西.我所拥有的是一个函数,它在两个列表species=['H2O','O2','CO2']和coeff=['1','3','-4'].我需要它像这样打印:
1H20+3O2=4CO2
我首先将负系数和物种放在一个列表中,而将积极放在另一个列表中.我似乎能够让两个打印正确.
试试这个:
species = ["H2O", "CO2", "O2"]
coeff = ['1', '-4', '3']
pos = [c + s for c, s in zip(coeff, species) if int(c) > 0]
neg = [c[1:] + s for c, s in zip(coeff, species) if int(c) < 0]
print ("+".join(pos))+"="+("+".join(neg))
Run Code Online (Sandbox Code Playgroud)
编辑:我拿出空格.
第二个编辑:coeff是一个字符串列表.
你也应该测试是否pos或者neg是空的,以取代他们0在适当的时候秒.似乎系数是整数.