get each pair from a string.
Ian Kelly
ian.g.kelly at gmail.com
Sun Oct 21 14:51:51 EDT 2012
On Sun, Oct 21, 2012 at 12:33 PM, Vincent Davis
<vincent at 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)
More information about the Python-list
mailing list