1

是否有一种简单的 Pythonic 方法可以从字符串生成所有给定长度的 n 元组?

例如,我想generateTuples("Hello, World!", 3)生成以下内容:

[ "Hel", "ell", "llo", "lo,", "o, ", ", W", " Wo", "Wor", "orl", "rld", "ld!" ]
4

4 回答 4

1
>>> a = "Hello, World!"
>>> def generate_tuples(string, n):
...     return [string[i:i+n] for i in range(len(string)-n+1)]
... 
>>> generate_tuples(a, 3)
['Hel', 'ell', 'llo', 'lo,', 'o, ', ', W', ' Wo', 'Wor', 'orl', 'rld', 'ld!']
于 2012-04-08T07:06:05.583 回答
1

这可能是您正在寻找的

>>> st="Hello, World!"
>>> [st[i:i+3] for i in xrange(0,len(st)-2)]
['Hel', 'ell', 'llo', 'lo,', 'o, ', ', W', ' Wo', 'Wor', 'orl', 'rld', 'ld!']

或者,如果您愿意,可以将其编写为函数:

>>> def generateTuples(st,n):
        return [st[i:i+n] for i in xrange(0,len(st)-n+1)]
于 2012-04-08T07:07:14.170 回答
1
>>> text = "Hello, World!"
>>> map(''.join,zip(*(text[i:] for i in range(3))))
['Hel', 'ell', 'llo', 'lo,', 'o, ', ', W', ' Wo', 'Wor', 'orl', 'rld', 'ld!']
于 2012-04-08T08:07:27.823 回答
0
>>> text = "Hello, World!"
>>>
>>> def subseqs(seq, length):
...     for i in xrange(len(seq) - length + 1):
...         yield seq[i:i+length]
...
>>> map(''.join, subseqs(text, 3))
['Hel', 'ell', 'llo', 'lo,', 'o, ', ', W', ' Wo', 'Wor', 'orl', 'rld', 'ld!']
于 2012-04-08T08:15:35.023 回答