2012-12-18 424 views
1

我有一個功能,是給多個陣列,我需要但這些成矩陣。陣列矩陣numpy

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,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 

回答

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]] 
+0

@ user1819717:是的。如果數組被稱爲'arr',那麼你正在尋找'arr.T'。 – unutbu