簡體   English   中英

如何從具有特定字符串格式的字典中減去

[英]How to subtract from dictionary with a specific string format

我如何從字符串string = '1A 3C'中的值中減去字典dictionary = {"A": 10, "B": 12, "C": 14}使得最終結果是dictionary = {"A": 9, "B": 12, "C": 11} (3C 表示將鍵“C”中的值減去 3)。

列表和字典不會是 static 但字母將始終按字母順序排列

我試圖做類似循環的事情,但我什至不知道從哪里開始

您可以使用正則表達式:

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)

更簡單的測試和工作示例,無需使用正則表達式和其他模塊,只是內置的,但僅當字典鍵保證為 1 個字母長時才有效,而要減去的數字可以長到你想要的長度:

string = '1A 3C'
dictio = {"A": 10, "B": 12, "C": 14}
for token in string.split(): # split string at spaces and unpack the resulting substrings
    value, key = token[:-1], token[-1] # value contains all letters of token except the last and key the last
    dictio[key] -= int(value) # convert value to a number and subtract the number from it's corresponding dictionary value

print(dictio)

Output:

{'A': 9, 'B': 12, 'C': 11}

您可以將'1A 3C'本身轉換為{'C': '3', 'A': '1'}類的字典,然后可以根據鍵進行減法。

dictionary = {"A": 10, "B": 12, "C": 14}

string = '1A 3C'

dict_string = {i[-1]:i[:-1] for i in string.split(' ')}


for k in dict_string:
    dictionary[k] -= int(dict_string[k])
    
print(dictionary)

{'A': 9, 'B': 12, 'C': 11}

嘗試這個:

dictionary["C"] -= 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM