如何从具有特定字符串格式的字典中减去
我如何dictionary = {"A": 10, "B": 12, "C": 14}从字符串中的值中减去字典string = '1A 3C',以便最终结果是dictionary = {"A": 9, "B": 12, "C": 11}?(3C 表示将 Key "C" 中的值减去 3)。
列表和字典不会是静态的,但字母将始终按字母顺序排列
我试图做类似循环的事情,但我什至不知道从哪里开始
回答
您可以使用正则表达式:
import re
# 1 or more digits followed by at least one non-digit char
pat = re.compile(r"^(d+)(D+)$")
# If there are negative numbers, e.g. "1A -3C"
# pat = re.compile(r"^(-?d+)(D+)$")
for token in string.split():
m = pat.match(token)
if m:
v = int(m.group(1)) # first capturing group: the numeric value
k = m.group(2) # second capturing group: the dict key
dictionary[k] -= v
从令牌中提取键和数值的非正则表达式方法是:
def fun(token):
num = 0
for i, c in enumerate(token):
if c.isdigit():
num = num*10 + int(c)
else:
return num, token[i:]
# do what needs doing if token does not have the expected form
# and in the loop
k, v = fun(token)