python - 在循环中使用和序列来计算值
问题描述
我需要关于我编写的使用化学计量计算密度的代码的帮助。每次执行时,它将创建一个唯一的文本文件,并在每个唯一的文本文件中写入与密度相对应的化学计量。因此,一旦它第一次执行,“stoich”将变为 2,然后变为 4,依此类推。它写入的每个文本文件都将具有计算密度的不同“stoich”值。
den_U = 19.1 #density of uranium 238 g/cc
den_C = 2.26 #density of carbon 12 g/cc
molm_U = 238.02 #molar mass of Uranium g/mol
molm_C = 12.0107 #molar mass of Carbon g/mol
stoich = [1,2,4,10,100,200,500,1000,2500,3000,4000]
for i in stoich:
input = 'density_stoichiometry_'+str(d)+'_'
file = open(input + '.txt', 'w')
T_C = molm_C*stoich # calculates total mass of carbon
T_com = T_C + molm_U # calculates total mass of chemical compound
per_C = T_C/T_com # calculates percent of carbon in compound
per_U = molm_U/T_com #calculates the percent of uranium in compound
den_com = den_U*per_U + den_C*per_C # calculates the total density
d = stoich
file.write('density='+str(den_com)+ '\n')
file.write('stoichiometry=' +str(d)+ '\n')
file.close()
stoich = 1
代码在 'T_C = molm_C*stoich' 处给了我错误,说我不能将序列乘以非 int 类型的 'float'。我假设我在“d = stoich”也会遇到同样的问题。如果有人可以提供帮助,我将不胜感激。
解决方案
以下作品:
den_U = 19.1 #density of uranium 238 g/cc
den_C = 2.26 #density of carbon 12 g/cc
molm_U = 238.02 #molar mass of Uranium g/mol
molm_C = 12.0107 #molar mass of Carbon g/mol
stoich = [1,2,4,10,100,200,500,1000,2500,3000,4000]
for i in stoich:
fname = 'density_stoichiometry_'+str(i)+'_.txt'
file = open(fname, 'w')
T_C = molm_C*i # calculates total mass of carbon
T_com = T_C + molm_U # calculates total mass of chemical compound
per_C = T_C/T_com # calculates percent of carbon in compound
per_U = molm_U/T_com #calculates the percent of uranium in compound
den_com = den_U*per_U + den_C*per_C # calculates the total density
file.write('density='+str(den_com)+ '\n')
file.write('stoichiometry=' +str(i)+ '\n')
file.close()
我使用i
而不是stoich
在循环体中,摆脱了无意义的d
,并将input
(内置函数的名称)替换为fname
. 我还将 的定义合并为fname
一行,因为将其定义分成两行(其中部分定义嵌入在函数调用中)会降低可读性。
推荐阅读
- haskell - 如何断言内部函数的类型取决于 Haskell 中外部函数的类型?
- scala - 是否有内置函数将 Int 限制为 Range?
- ruby-on-rails - Elasticsearch 6.2.4 [400] {"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"文本为空 (可能是 HTTP/0.9)"}]
- python - 在pygame中检查碰撞和停止速度
- cypress - Cypress 通过 css 选择器获取元素标签名称
- c# - 在 C# 客户端应用程序中创建用户身份验证
- html - 用计数处理拆分列无序列表的Ruby方式?
- python - Python - 同时运行代码(TTS 和打印功能)
- c++ - 保留函数指针模板参数
- node.js - 如何在猫鼬的其他对象数组中更新特定对象的元素