python - Multiply an integer in a list by a word in the list -
i'm not sure how multiply number following string string. want find rmm of compound started making dictionary of rmms have them added together. issue compounds such h2o.
name = input("insert name of molecule/atom find rmm/ram: ") compound = re.sub('([a-z])', r' \1', name) compound = compound.split(' ') r = re.split('(\d+)', compound)
for example:
when name = h2o compound = ['', 'h2', 'o'] r = ['h', '2', 'o']
i want multiply 2 h making value "['h', 'h', 'o']."
tldr: want integers following names in list print listed object 'x' amount of times (e.g. [o, 2] => o o, [c, o, 2] => c o o)
the question complicated, let me know if can clarify it. thanks.
how following, after define compound
:
test = re.findall('([a-za-z]+)(\d*)', compound) expand = [a*int(b) if len(b) > 0 else (a, b) in test]
match on letters of 1 or more instances followed optional number of digits - if there's no digit return letters, if there digit duplicate letters appropriate value. doesn't quite return expected - instead return ['hh', 'o']
- please let me know if suits.
edit: assuming compounds use elements consisting of either single capital letter or single capital followed number of lowercase letters, can add following:
final = re.findall('[a-z][a-z]*', ''.join(expand))
which return elements each separate entry in list, e.g. ['h', 'h', 'o']
edit 2: assumption of previous edit, can reduce whole thing down couple of lines:
name = raw_input("insert name of molecule/atom find rmm/ram: ") test = re.findall('([a-z][a-z]*)(\d*)', name) final = re.findall('[a-z][a-z]*', ''.join([a*int(b) if len(b) > 0 else (a, b) in test]))
Comments
Post a Comment