0

给定一个字符串,如"8584320342564023450211233923239923239110001012346596",如何获得所有连续的 4 位子序列?

例如,上面的字符串将产生:8548, 5843, 8432, 0342, ...

4

6 回答 6

6

我认为这可以满足您的要求:

es = '8584320342564023450211233923239923239110001012346596'
strings = [es[x:x+4] for x in xrange(0, len(es)-3)]

输出

>> strings
Out[42]: 
['8584',
 '5843',
 '8432',
 '4320',
 '3203',
 '2034',
 '0342',
 '3425',
 '4256',
 '2564',
 '5640',
 '6402',
 '4023',
 '0234',
 '2345',
 '3450',
 '4502',
 '5021',
 '0211',
 '2112',
 '1123',
 '1233',

  ...
于 2012-04-19T15:51:09.933 回答
2

您可以使用以下代码获取nith位置开始的字符子序列:

str[i:i+n]

请注意,第 0位置是字符串的开头,而不是第 1。我的意思是str[0:0+n]会给你前 n 个字符而不是str[1:1+n]

这是代码:

s =  "8584320342564023450211233923239923239110001012346596"

for i in range(len(s) - 3):
    print(s[i:i+4])
于 2012-04-19T15:50:09.703 回答
2
data = "8584320342564023450211233923239923239110001012346596"
span = 4
for i in range(len(data) - span + 1):
    print data[i:i+span]
于 2012-04-19T15:50:18.697 回答
1

这是一个正则表达式解决方案:

import re
re.findall("[0-9]{4}","8584320342564023450211233923239923239110001012346596")

编辑:感谢评论,我看到你真正想要的是所有重叠的匹配。我在这里找到了一个现有的 stackoverflow 答案: Python regex find all重叠匹配?

使用它作为所需正则表达式的提示。在您的情况下,您可以使用:

>>> re.findall("(?=(\d{4}))","8584320342564023450211233923239923239110001012346596")
['8584', '5843', '8432', '4320', '3203', '2034', '0342', '3425', '4256', '2564', '5640', '6402', '4023', '0234', '2345', '3450', '4502', '5021', '0211', '2112', '1123', '1233', '2339', '3392', '3923', '9232', '2323', '3239', '2399', '3992', '9923', '9232', '2323', '3239', '2391', '3911', '9110', '1100', '1000', '0001', '0010', '0101', '1012', '0123', '1234', '2346', '3465', '4659', '6596']
于 2012-04-19T15:57:37.277 回答
1
>>> from itertools import islice
>>> line = "8584320342564023450211233923239923239110001012346596"
>>> map(''.join, zip(*(islice(line,i,None) for i in range(4))))
['8584', '5843', '8432', '4320', '3203', '2034', '0342', '3425', '4256', '2564', '5640', '6402', '4023', '0234', '2345', '3450', '4502', '5021', '0211', '2112', '1123', '1233', '2339', '3392', '3923', '9232', '2323', '3239', '2399', '3992', '9923', '9232', '2323', '3239', '2391', '3911', '9110', '1100', '1000', '0001', '0010', '0101', '1012', '0123', '1234', '2346', '3465', '4659', '6596']
于 2012-04-20T04:47:26.147 回答
0

这会将输出设置为包含一个列表列表,其中每个 4 个字符序列都有一个叶子:

output = []
for i in range(len(input) - 3):
    output.append(input[i:i+4])
于 2012-04-19T15:50:09.283 回答