Skip to main content
 首页 » 编程设计

python之使用字典替换列表中的数字

2025年05月04日20kevingrace

我正在尝试使用字典来替换字符串中的最后一位数字。我将元素提取到一个列表中,替换,然后将列表连接回一个字符串。代码运行但它只替换使用字典中的第二个元素。

text = "foo 123 doo 342 ghh 568 loo 243" 
s = re.split(r'(\d+)', text) 
textDict = {"2$":"fg" , "3$":"gh", "8$":"hj"} 
for key in textDict: 
    t = [re.sub(key , textDict[key], x) for x in s] 
u = ["".join(t)] 
u = str(u) 
print u 

我期待以下输入

foo 12gh doo 34fg ghh 56hj loo 24gh 

但是我现在正在获取

foo 12gh doo 342 ghh 568 loo 24gh 

稍微扩展一下问题:

如果我想更改两个 最后一位数,那么这两种解决方案都无法工作。它们都返回原始字符串:

import re 
 
text = "foo 123 doo 342 ghh 568 loo 243" 
textDict = {"23":"fg" , "43":"gh", "68":"hj"} 

使用解决方案#1:

s = re.split(r'(\d+)', text) 
for i in range(len(s) - 2): 
  s[i] = s[i][:-2] + textDict[s[i][-2]] if s[i][-2] in textDict else s[i] 
 
u = "".join(s) 
print u 

使用解决方案#2:

result_str = '' 
for txt in text.split(' '): 
    if txt.isdigit() is True: 
        txt = txt[:-2] + textDict.get(txt[-2], txt[-2]) 
    result_str += (txt + ' ') 
 
result_str.strip()     

请您参考如下方法:

此解决方案无需使用 re 即可工作。我修改了你的 textDict

In [19]: text = "foo 123 doo 342 ghh 568 loo 243" 
 
In [20]: textDict = {"2":"fg" , "3":"gh", "8":"hj"} # modified textDict 
 
In [21]: result_str = '' 
 
In [22]: c_len = 1 # just modify this according to length of dict key 
 
In [23]: for txt in text.split(' '): 
    ...:     if txt.isdigit() is True: 
    ...:         txt = txt[:-c_len] + textDict.get(txt[-c_len:], txt[-c_len:]) 
    ...:     result_str += (txt + ' ') 
    ...: 
 
In [24]: result_str.strip()    # to remove last space 
Out[24]: 'foo 12gh doo 34fg ghh 56hj loo 24gh ' 

要回答你的第二个问题,只需根据字典键长度修改c_len。