[英]How do I append a character within parentheses in Python?
I have the following input: 我有以下输入:
[ [ 'A(x)|B(x,y)|C(z)'],['A(x,y)|B(John,y)|C(z)' ] ]
I want the following output 我想要以下输出
[ [ A(x1)|B(x1,y1)|C(z1)'],['A(x2,y2)|B(John,y2)|C(z2)' ] ]
If I have a list of lists as the input, how can I append a counter initialized to one successively in this manner? 如果我有一个列表列表作为输入,如何以这种方式连续地将一个计数器初始化为一个?
Since it's a list of lists, you have to use list comprehension, enumerate , regex. 由于它是列表列表,您必须使用列表理解, 枚举 ,正则表达式。
>>> import re
>>> x = [ [ 'A(x)|B(x,y)|C(z)'],['A(x,y)|B(John,y)|C(z)' ] ]
>>> [[re.sub(r'([xyz])', r'\g<1>{}'.format(i+1), k) for k in j] for i,j in enumerate(x)]
[['A(x1)|B(x1,y1)|C(z1)'], ['A(x2,y2)|B(John,y2)|C(z2)']]
------
>>> x = [ [ 'A(x)|B(x,y)|C(z)', 'B(x,y)'],['A(x,y)|B(John,y)|C(z)' ], ['A|B'], ['A(x,y)|B(John,y)|C(z)'] ]
>>> [[re.sub(r'([xyz])', r'\g<1>{}'.format(i), k) for k in j] for i,j in enumerate(x, 1)]
[['A(x1)|B(x1,y1)|C(z1)', 'B(x1,y1)'], ['A(x2,y2)|B(John,y2)|C(z2)'], ['A|B'], ['A(x4,y4)|B(John,y4)|C(z4)']]
Iterate over the main list , then iterate over sublist and then match and replace (append the index number next to x or y or z) each string present inside the sublist. 迭代主列表,然后迭代子列表,然后匹配并替换(附加x或y或z旁边的索引号)子列表中存在的每个字符串。
I'd personally use regex for this. 我个人使用正则表达式。
re.sub
substitutes a string for another string (that contains regex markup, like \\g<1>
). re.sub
将字符串替换为另一个字符串(包含正则表达式标记,如\\g<1>
)。
re.sub("(?<!\w)([xyz])",r"\g<1>2",before)
Making your full code: 制作完整的代码:
import re
before = "[ [ 'A(x)|B(x,y)|C(z)'],['A(x,y)|B(John,y)|C(z)' ] ]"
print(re.sub("(?<!\w)([xyz])",r"\g<1>2",before))
(?<!\w)([xyz])
We are doing a negative look behind to make sure that it isn't part of a word, (?<!\\w)
. 我们正在做一个消极的看法,以确保它不是一个单词的一部分,
(?<!\\w)
。 Then we check for our desired variable names, ([xyz])
. 然后我们检查所需的变量名称
([xyz])
。 If it follows this pattern, then we replace it with: 如果它遵循这种模式,那么我们将其替换为:
\g<1>2
I used \\g<1>
instead of \\1
because Python won't interpret \\12
as we want. 我使用
\\g<1>
而不是\\1
因为Python不会像我们想要的那样解释\\12
。 It will view it as regex group 12, instead of regex group 1 then the number 2. 它将其视为正则表达式组12,而不是正则表达组1,然后是数字2。
Regex101 is a great tool for understanding regex's. Regex101是理解正则表达式的绝佳工具。 Click the link to view how it works.
单击链接以查看其工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.