Python: 化学元素计数器
Python: chemical elements counter
我想获取给定混合物的元素。例如,对于字典给出的空气(O2 和 N2)和己烷(C6H14)的混合物及其各自的摩尔数
mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}
我想获得以下信息:
{O: 2, N: 7.52, C:0.06, H: 0.14}
另一个例子:
mix = {'C6H14': 1, 'C9H20': 1}
必须产量
{H: 34, C: 15}
enter code here
字典的顺序并不重要。我尝试使用 re.split,但没有取得任何进展。如果有人能帮助我,我将不胜感激。
编辑:嗨,也许我的问题不清楚,但我想要的是计算混合物中的原子数。我尝试使用正则表达式库中的 re.findall。我试图将数字与其他字符分开。
示例:
mix = {'C6H14': 1, 'C9H20': 1}
atmix = []
mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}
for x in mix.keys():
tmp = re.findall(r'[A-Za-z]+|\d+', x)
tmp = list(zip(tmp[0::2], tmp[1::2]))
atmix.append(tmp)
知道我有:
>>> atmix
[(['O'], ['2']), (['N'], ['2']), (['C', 'H'], ['6', '14'])]
这是一个包含物质元组及其原子数的列表。从这里开始,我需要获取每种物质并将其与原子数乘以混合字典给出的摩尔数相关联,但我不知道如何实现。我试图从混合物中分离物质及其原子的方式似乎很愚蠢。我需要一种更好的方法来对这些物质及其原子进行分类,并发现如何将其与摩尔数联系起来。
提前致谢
您可以迭代 mix
字典,同时使用 carefully-crafted 正则表达式将每个元素与其计数分开。
import re
from collections import defaultdict
mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}
out = defaultdict(float)
regex = re.compile(r'([A-Z]+?)(\d+)?')
for formula, value in mix.items():
for element, count in regex.findall(formula):
count = int(count) if count else 1 # supporting elements with no count,
# eg. O in H2O
out[element] += count * value
print(out)
产出
defaultdict(<class 'float'>, {'O': 2.0, 'N': 7.52, 'C': 0.06, 'H': 0.14})
我想获取给定混合物的元素。例如,对于字典给出的空气(O2 和 N2)和己烷(C6H14)的混合物及其各自的摩尔数
mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}
我想获得以下信息:
{O: 2, N: 7.52, C:0.06, H: 0.14}
另一个例子:
mix = {'C6H14': 1, 'C9H20': 1}
必须产量
{H: 34, C: 15}
enter code here
字典的顺序并不重要。我尝试使用 re.split,但没有取得任何进展。如果有人能帮助我,我将不胜感激。
编辑:嗨,也许我的问题不清楚,但我想要的是计算混合物中的原子数。我尝试使用正则表达式库中的 re.findall。我试图将数字与其他字符分开。 示例:
mix = {'C6H14': 1, 'C9H20': 1}
atmix = []
mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}
for x in mix.keys():
tmp = re.findall(r'[A-Za-z]+|\d+', x)
tmp = list(zip(tmp[0::2], tmp[1::2]))
atmix.append(tmp)
知道我有:
>>> atmix
[(['O'], ['2']), (['N'], ['2']), (['C', 'H'], ['6', '14'])]
这是一个包含物质元组及其原子数的列表。从这里开始,我需要获取每种物质并将其与原子数乘以混合字典给出的摩尔数相关联,但我不知道如何实现。我试图从混合物中分离物质及其原子的方式似乎很愚蠢。我需要一种更好的方法来对这些物质及其原子进行分类,并发现如何将其与摩尔数联系起来。
提前致谢
您可以迭代 mix
字典,同时使用 carefully-crafted 正则表达式将每个元素与其计数分开。
import re
from collections import defaultdict
mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}
out = defaultdict(float)
regex = re.compile(r'([A-Z]+?)(\d+)?')
for formula, value in mix.items():
for element, count in regex.findall(formula):
count = int(count) if count else 1 # supporting elements with no count,
# eg. O in H2O
out[element] += count * value
print(out)
产出
defaultdict(<class 'float'>, {'O': 2.0, 'N': 7.52, 'C': 0.06, 'H': 0.14})