On 10/21/2012 11:51 AM, Ian Kelly wrote:
On Sun, Oct 21, 2012 at 12:33 PM, Vincent Davis
<vinc...@vincentdavis.net> wrote:
I am looking for a good way to get every pair from a string. For example,
input:
x = 'apple'
output
'ap'
'pp'
'pl'
'le'

I am not seeing a obvious way to do this without multiple for loops, but
maybe there is not :-)

Use the "pairwaise" recipe from the itertools docs:

def pairwise(iterable):
     "s -> (s0,s1), (s1,s2), (s2, s3), ..."
     a, b = tee(iterable)
     next(b, None)
     return izip(a, b)

In the end I am going to what to get triples, quads....... also.

Generalizing:

def nwise(iterable, n=2):
     iters = tee(iterable, n)
     for i, it in enumerate(iters):
         for _ in range(i):
             next(it, None)
     return izip(*iters)




Hmmm.  And it seemed so straightforward to me as:

>>> groupsize=3
>>> a = "applesauce"
>>> for i in range(len(a)-groupsize+1): a[i:i+groupsize]
...
'app'
'ppl'
'ple'
'les'
'esa'
'sau'
'auc'
'uce'

Other than adding depth to my knowledge of the ever growing standard library, is there a reason to prefer pairwise over my simple loop?

Emile

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to