我想在python中撰寫分子式(字串)中原子數的摘要。字串是一個字母后跟一個數字(當沒有數字時,它被算作一個)。
輸入:C3H7NO2C3H7NO2S 輸出:C6H14N2O4S
我僅有的字母是:O、C、N、H 和 S。
uj5u.com熱心網友回復:
AC#“oneliner”,你當然不能作為作業解決方案發送:
var s = "C3H7NO2C3H7NO2S";
var s2 = string.Join(" ",Regex.Split(s, @"([A-Z]\d*)")
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => Regex.Match(x, @"([A-Z])(\d*)"))
.Select(m => new {elt = m.Groups[1].Value, cnt = m.Groups.Count > 2 ? m.Groups[2].Value : "1"})
.Select(e => new {e.elt, cnt = string.IsNullOrEmpty(e.cnt) ? 1 : int.Parse(e.cnt)})
.GroupBy(e => e.elt)
.Select(g => $"{g.Key}{g.Sum(x=>x.cnt)}")
);
// s2 contains "C6 H14 N2 O4 S1"
小提琴
- 首先獲取元素計數對(其中計數是可選的)
- 然后將它們拆分為元素和計數(缺少計數 = 1)
- 然后按元素分組并對計數求和
- 然后加入一個字串
uj5u.com熱心網友回復:
定義轉換(aa_seq):
temp = re.findall('\d |\D ', str_atoms) #split string to numbers and chars
#print(temp)
# dictionary
dicta = {}
# list to dictionary
for i in range(int(0.5 * len(temp))):
key = temp[2 * i] # set atom as key
val = int(temp[2 * i 1]) #set value as the number that follows
# print(key ' = ' str(val))
if (key in dicta): #add value to existing key
dicta[key] = val
else: # if key does not exist create this
dicta[key] = val
print(dicta)
# dictionary to string
final_str = ''
for x in dicta:
final_str = x str(dicta[x])
print(str_atoms)
print(final_str)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370913.html
