gpt4 book ai didi

python - 数组到矩阵 numpy

转载 作者:行者123 更新时间:2023-12-01 05:52:00 25 4
gpt4 key购买 nike

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

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

最佳答案

不要打印出每一行,而是将它们收集到一个列表中(例如结果):

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

关于python - 数组到矩阵 numpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com