我如何减去字典 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
从 token 中提取键和数值的非正则表达式方法是: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)
关于python - 如何从具有特定字符串格式的字典中减去,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66281118/