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

2024-04-28 02:31:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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()    

Tags: key字符串textinretxtforfoo
2条回答

一种方法是反转for循环。您可以遍历文本段,而不是遍历键。我不认为你需要使用正则表达式,因为你有一个非常具体的情况。你知道吗

import re

text = "foo 123 doo 342 ghh 568 loo 243"
s = re.split(r'(\d+)', text)

textDict = {"2":"fg" , "3":"gh", "8":"hj"}
for i in range(len(s) - 1):
  s[i] = s[i][:-1] + textDict[s[i][-1]] if str(s[i][-1]) in textDict else s[i]

u = "".join(s)
u = str(u)
print u

这将产生以下输出:

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

我相信这也更有效,因为不是有两个嵌套循环(这使我们的复杂性达到O(n*m)),而是迭代一个列表,这使我们O(n)。你知道吗

此解决方案不使用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 '

要回答上一个问题,只需根据dict键长度修改c_len。你知道吗

相关问题 更多 >