Text manipulation in Python -
i have following list in python :
[{"coefficient": -1.0, "compartment": "c", "molecule": "a", "evidence": []}, {"coefficient": -1.0, "compartment": "c", "molecule": "b", "evidence": []}, {"coefficient": -1.0, "compartment": "c", "molecule": "c", "evidence": []}, {"coefficient": 1.0, "compartment": "c", "molecule": "d", "evidence": []}, {"coefficient": 1.0, "compartment": "c", "molecule": "e", "evidence": []}, {"coefficient": 1.0, "compartment": "c", "molecule": "f", "evidence": []}]
i want convert :
a + b + c --> d + e + f
which easiest way in python?
the rules are:
- if coefficient negative, want treat corresponding molecule reactant.
- if coefficient positive, want treat corresponding molecule product.
- reactants come on left hand side of
-->
mark. - products come on right hand side of
-->
mark.
the following should do:
l = [{"coefficient": -1.0, "compartment": "c", "molecule": "a", "evidence": []}, {"coefficient": -1.0, "compartment": "c", "molecule": "b", "evidence": []}, {"coefficient": -1.0, "compartment": "c", "molecule": "c", "evidence": []}, {"coefficient": 1.0, "compartment": "c", "molecule": "d", "evidence": []}, {"coefficient": 1.0, "compartment": "c", "molecule": "e", "evidence": []}, {"coefficient": 1.0, "compartment": "c", "molecule": "f", "evidence": []}] def format_mol_list(molecules): # create lists hold molecules of each type, in order reactants = [] products = [] # sort items reactants , products item in molecules: if item["coefficient"] > 0: products.append(item["molecule"]) else: reactants.append(item["molecule"]) return " + ".join(reactants) + " --> " + " + ".join(products) print format_mol_list(l)
output:
a + b + c --> d + e + f
Comments
Post a Comment