1

我有一个提供多个数组的函数,我需要将它们放入一个矩阵中。

def equations(specie, elements):
 for x in specie:
   formula = parse_formula(x)
   print extracting_columns(formula, elements)

我得到了什么:

equations(['OH', 'CO2','C3O3','H2O3','CO','C3H1'], ['H', 'C', 'O']) 
[ 1.  0.  1.]
[ 0.  1.  2.]
[ 0.  3.  3.]
[ 2.  0.  3.]
[ 0.  1.  1.]
[ 1.  3.  0.]

我需要它给我 ([[1,0,1][[ 0., 1., 2.][ 0. , 3. , 3.][ 2. , 0. ,3.][ 0. , 1. ,1.][ 1. , 3., 0.]])

我已经搞砸了一段时间,无法弄清楚。

如果您需要我过去的功能,它们如下:

def extracting_columns(specie, elements):
  species_vector=zeros(len(elements))
  for (el,mul) in specie:
    species_vector[elements.index(el)]=mul

  return species_vector
4

1 回答 1

2

与其打印每一行,不如将它们收集到一个列表中(例如result):

def equations(specie, elements):
    result = []
    for x in specie:
        formula = parse_formula(x)
        result.append(extracting_columns(formula, elements))
    return np.array(result)

例如,

import numpy as np
import re

def equations(specie, elements):
    result = []
    for x in specie:
        formula = parse_formula(x)
        result.append(extracting_columns(formula, elements))
    return np.array(result)

def extracting_columns(formula, elements):
    return [formula.get(e, 0) for e in elements]

def parse_formula(formula):
    elts = iter(re.split(r'([A-Z][a-z]*)',formula)[1:])
    return {element:toint(num) for element, num in zip(*[elts]*2)}

def toint(num):
    try:
        return int(num)
    except ValueError:
        return 1

print(equations(['OH', 'CO2','C3O3','H2O3','CO','C3H1'], ['H', 'C', 'O']))

产量

[[1 0 1]
 [0 1 2]
 [0 3 3]
 [2 0 3]
 [0 1 1]
 [1 3 0]]
于 2012-12-18T02:30:01.863 回答