-1

我在 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": []}]

我想将其转换为:

A + B + C --> D + E + F

在 python 中执行此操作的最简单方法是什么?

规则是:

  • 如果系数为负,我想将相应的分子视为反应物。
  • 如果系数为正,我想将相应的分子视为产品。
  • -->反应物出现在标记的左侧。
  • -->产品位于标记的右侧。
4

2 回答 2

3

以下应该做:

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 that will hold the molecules of each type, in order
    reactants = []
    products = []

    # Sort the items into reactants and products
    for 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)

输出:

A + B + C --> D + E + F
于 2013-08-28T17:27:39.903 回答
1
li = ['{"coefficient": -1.0, "compartment": "c", "molecule": "A", "evidence": []}',
      '{"coefficient": -5.0, "compartment": "c", "molecule": "B", "evidence": []}',
      '{"coefficient": -1.0, "compartment": "c", "molecule": "C", "evidence": []}',
      '{"coefficient": 1.0, "compartment": "c", "molecule": "D", "evidence": []}',
      '{"coefficient": 3.0, "compartment": "c", "molecule": "E", "evidence": []}',
      '{"coefficient": 4.0, "compartment": "c", "molecule": "F", "evidence": []}']

from itertools import imap
from ast import literal_eval

def eq(li):
    a,b = [],[]
    for d in imap(literal_eval,li):
        c = int(d['coefficient'])
        if c==-1:
            a.append(d['molecule'])
        elif c<-1:
            a.append('%d %s' % (-c,d['molecule']))
        elif c==1:
            b.append(d['molecule'])
        elif c>1:
            b.append('%d %s' % (c,d['molecule']))              
    return ''.join(('  +  '.join(a),'  -->  ','  +  '.join(b)))

print eq(li)

结果

A  +  5 B  +  C  -->  D  +  3 E  +  4 F
于 2013-08-28T17:33:55.197 回答