从字符串生成所有n元组

时间:2012-04-08 07:01:53

标签: python string

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

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

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

4 个答案:

答案 0 :(得分: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!']

答案 1 :(得分: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)]

答案 2 :(得分: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!']

答案 3 :(得分: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!']