首先感谢这篇文章的作者:python实现字符串中所有数字所在位置
- 文章中的indexNumber(str)可以实现如下功能
s = indexNumber('a2aa2bbb3cec4dddd')
print(s)
> [['2',1],['2',4],['3',8],['4',12]]
- 但是有时候我们希望输出的数字是具有连续性的
比如 '113a45', indexNumber会返回这样一个list:[['1', 0], ['1', 1], ['3', 2], ['4', 4], ['5', 5]]
而期望是:[['113', 0], ['45', 4]]
- 所以写了一个connect_num(ls)能实现对于连续数字的连接
在获得indexNumber的list后,用作connect_num的输入list,可以获得期望的输出list
def connect_num(ls):
out = []
j = 0
for i in range(len(ls)):
if not len(out):
out.append(ls[0])
elif out[j][1] == ls[i][1] - len(out[j][0]):
out[j][0] = out[j][0] + ls[i][0]
else:
j+=1
out.append(ls[i])
return out
a = [['1', 0], ['1', 1], ['3', 2], ['4', 4], ['5', 5]]
connect_num(a)
> [['113', 0], ['45', 4]]