python - 如何从具有特定字符串格式的字典中减去

标签 python

我如何减去字典 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/

相关文章:

python - 使用 python 删除 vba 模块?

python - 按顺序固定列

python - Ubuntu Command 'pip' not found,但有18个类似的

python - "Empty reply from server"用于 Flask + uWSGI 设置

python - 将 2 级多索引系列重新组合到数据帧,以便第二级索引成为名称?

python - 如何将 QPlainTextEdit 向右对齐?

python - 拆分后我的 readline() 的空字符串是什么

python - 如何中止通过 python 中的 cmds.file 启动的 Maya 文件加载

Python获取文件中的单词数

python - Pylance:在这种情况下不允许使用 "ClassVar"?