Python 如何使用特定的字符串格式从字典中减去
如何从字符串Python 如何使用特定的字符串格式从字典中减去,python,Python,如何从字符串string='1a3c'中的值减去dictionarydictionary={“a”:10,“B”:12,“C”:14},最终结果是dictionary={“a”:9,“B”:12,“C”:11}?(3C表示用3减去键“C”中的值) 列表和字典不会是静态的,但字母总是按字母顺序排列的 我试图做一些类似循环的事情,但我甚至不确定从哪里开始您可以使用正则表达式: import re # 1 or more digits followed by at least one non-dig
string='1a3c'
中的值减去dictionarydictionary={“a”:10,“B”:12,“C”:14}
,最终结果是dictionary={“a”:9,“B”:12,“C”:11}
?(3C表示用3减去键“C”中的值)
列表和字典不会是静态的,但字母总是按字母顺序排列的
我试图做一些类似循环的事情,但我甚至不确定从哪里开始您可以使用正则表达式:
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)
试试这个:
dictionary[“C”]-=3
更简单的测试和工作示例,无需使用正则表达式和其他模块,只需内置,但仅在字典键保证为1个字母长时有效,而要减去的数字可以是您想要的长度:
string='1a3c'
用词={A:10,B:12,C:14}
对于string.split()中的标记:#在空格处拆分字符串并解压缩生成的子字符串
value,key=token[:-1],token[-1]#value包含除最后一个和最后一个键之外的所有token字母
dictiono[key]-=int(value)#将值转换为一个数字,并从相应的字典值中减去该数字
印刷(辞典)
输出:
{'A':9,'B':12,'C':11}
您可以将'1a3c'
本身转换为类似于{'C':'3','A':'1'}
的字典,然后您可以根据键进行减法
dictionary={A:10,B:12,C:14}
字符串='1A 3C'
dict_string={i[-1]:i[:-1]表示string.split(“”)中的i
对于dict_字符串中的k:
字典[k]=int(dict_字符串[k])
印刷(字典)
这是如何回答这个问题的?它根本不使用
string
。有没有其他方法可以不用正则表达式来实现这一点?对我来说似乎有点超前me@Jon是的,有,看我的答案@Jon我不是正则表达式的朋友;)!您可以手动迭代每个令牌,直到找到一个非数字。但代码将更加复杂。
{'A': 9, 'B': 12, 'C': 11}