Python传递数组参数至molecularWeight函数报错,求批量计算方案
解决列表传入函数时的TypeError问题
你遇到的TypeError是因为传入的concentration和time是Python普通列表,列表不支持元素级的算术运算——直接用/会把整个列表当作单一对象处理,而不是逐个元素计算,所以触发了类型不匹配的错误。
下面是几种可行的解决方案:
方案1:利用numpy数组的向量化运算(推荐)
既然你已经在使用numpy,直接从原数组切片得到numpy数组,numpy支持向量化运算,能直接批量处理所有元素:
import numpy as np # 确保导入numpy concentration_time = np.array([[0,83], [0.04,89], [0.06,95], [0.08,104], [0.1,114], [0.12,126], [0.14,139], [0.16,155], [0.20,191]]) # 直接从numpy数组切片,得到numpy数组而非普通列表 concentration = concentration_time[:, 0] time = concentration_time[:, 1] t0 = 83 def molecularWeight(c,t): answer = ((t/t0)-1)/c return answer # 直接批量计算,返回numpy数组 result = molecularWeight(concentration, time) print(result)
注意:第一个元素的c=0会触发除以0的警告,结果为inf,你可以根据需求单独处理该情况。
方案2:用列表推导式逐个计算
如果不想依赖numpy,可通过zip配对(c,t),逐个调用函数计算:
concentration_time = np.array([[0,83], [0.04,89], [0.06,95], [0.08,104], [0.1,114], [0.12,126], [0.14,139], [0.16,155], [0.20,191]]) concentration = [item[0] for item in concentration_time] time = [item[1] for item in concentration_time] t0 = 83 def molecularWeight(c,t): # 处理c=0的情况,避免除以0错误 if c == 0: return None # 可替换为你需要的默认值 answer = ((t/t0)-1)/c return answer # 用列表推导式批量生成结果 results = [molecularWeight(c, t) for c, t in zip(concentration, time)] print(results)
方案3:修改函数使其支持列表输入
在函数内部遍历输入的列表,逐个计算后返回结果列表:
concentration_time = np.array([[0,83], [0.04,89], [0.06,95], [0.08,104], [0.1,114], [0.12,126], [0.14,139], [0.16,155], [0.20,191]]) concentration = [item[0] for item in concentration_time] time = [item[1] for item in concentration_time] t0 = 83 def molecularWeight(c_list, t_list): results = [] for c, t in zip(c_list, t_list): if c == 0: results.append(None) continue answer = ((t/t0)-1)/c results.append(answer) return results # 直接传入列表即可批量计算 results = molecularWeight(concentration, time) print(results)
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

