你好, 我想从位置零的另一个列表中的列表中计算给定的短语。
list_given_atoms= ['C', 'Cl', 'Br']
list_of_molecules= ['C(B2Br)[Cl{H]Cl}P' ,'NAME']
当 python 找到一个匹配时,它应该被安全地保存在一个字典中,比如
countdict = [ 'Cl : 2', 'C : 1', 'Br : 1']
我试过了
re.findall(r'\w+', list_of_molecules[0])
已经,但这会导致像“B2Br”这样的词,这绝对不是我想要的。
谁能帮帮我?
请您参考如下方法:
[a-zA-Z]+ 应该用来代替 \w+ 因为 \w+ 会同时匹配字母和数字,而你只是在寻找字母:
import re
list_given_atoms= ['C', 'Cl', 'Br']
list_of_molecules= ['C(B2Br)[Cl{H]Cl}P' ,'NAME']
molecules = re.findall('[a-zA-Z]+', list_of_molecules[0])
final_data = {i:molecules.count(i) for i in list_given_atoms}
输出:
{'C': 1, 'Br': 1, 'Cl': 2}
