需要根据给定的模式创建字符串
如果模式是222243243则需要创建的字符串是“2{4,6}[43]+2{1,3}[43]+”。 创建上述字符串的逻辑是,检查模式中有多少个2的集合,并对它们进行计数,然后再添加两个2。第一部分包含4个2,第二部分包含1个2。因此,前两个可以是4到6(4+2)2,第二个可以是1到3(1+2)。当有3个或4个时,[43]+需要添加
加工:
import re
data='222243243'
TwosStart=[]#contains twos start positions
TwosEnd=[]#contains twos end positions
TwoLength=[]#number of 2's sets
for match in re.finditer('2+', data):
s = match.start()#2's start position
e = match.end()#2's end position
d=e-s
print(s,e,d)
TwosStart.append(s)
TwosEnd.append(e)
TwoLength.append(d)
使用上面的代码,我知道给定模式中有多少个2的集合,以及它们的开始和结束位置。但我不知道如何使用上述信息自动创建字符串
例:
if pattern '222243243' string should be "2{4,6}[43]+2{1,3}[43]+"
if pattern '222432243' string should be "2{3,5}[43]+2{2,4}[43]+"
if pattern '22432432243' string should be "2{2,4}[43]+2{1,3}[43]+2{2,4}[43]+"
一种方法是使用itertools.groupby:
输出
使用基本代码:
输出
2{4,6}[43]+2{1,3}[43]+
相关问题 更多 >
编程相关推荐