猿问

一个replace顺序问题

我大概这样一个数字序列 其中有1 2 3 之类的数字 但是又有些是带有 () 或者 (()) 【】 这类括弧的数字

我想通过replace来实现像是将 1 2 3 替换成 2 3 4 的功能

replace(1,2)

replace(2,3)

replace(3,4)

但是里面遇到一个顺序问题 1被替换成2后 再次被替换成3 又被替换成4

最终输入111结果会是444

于是我将顺序倒序

replace(3,4)

replace(2,3)

replace(1,2)

虽然解决了这个问题 但是发现括弧造成的麻烦也与这个顺序问题相似

同时两组顺序问题 就难以都解决了 请问有什么好方法吗?

最后放上序列


[ "((1))","((#1))","((2))","((#2))","((3))","((4))","((#4))","((5))","((#5))","((6))","((#6))","((7))",  "(1)","(#1)","(2)","(#2)","(3)","(4)","(#4)","(5)","(#5)","(6)","(#6)","(7)",  "1","#1","2","#2","3","4","#4","5","#5","6","#6","7",  "[1]","[#1]","[2]","[#2]","[3]","[4]","[#4]","[5]","[#5]","[6]","[#6]","[7]",  "[[1]]","[[#1]]","[[2]]","[[#2]]","[[3]]","[[4]]","[[#4]]","[[5]]","[[#5]]","[[6]]","[[#6]]","[[7]]" ]

我实际想解决的是 将一个字串中 list[n]的内容替换成list[n+1]



桃花长相依
浏览 382回答 2
2回答

子衿沉夜

这个问题不难解决,让你的 replace 函数同时支持多组替换输入,比如:replace([[1, 2], [2, 3], [3, 4]])表示 1 替换为2,2 替换为 3,3 替换为 4。然后 replace 函数内并不是针对原来的文本进行操作,而是一个字节一个字节的读,检查每一个字节是否需要替换,然后把结果合成为新字符串即可。既然你标记的是 Python,那我就稍后给你写个示例代码吧 0.0

LEATH

不太常用 Python,写的不是很好 0.0稍微凑活下下吧- -
随时随地看视频慕课网APP
我要回答