Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #31855
| References | <CALyJZZURWQxgPTQcQo8kOdHkaOYbB6YE=U=vi6VrX9FoDH1gAQ@mail.gmail.com> |
|---|---|
| From | Ian Kelly <ian.g.kelly@gmail.com> |
| Date | 2012-10-21 12:51 -0600 |
| Subject | Re: get each pair from a string. |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2595.1350845543.27098.python-list@python.org> (permalink) |
On Sun, Oct 21, 2012 at 12:33 PM, Vincent Davis
<vincent@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)
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: get each pair from a string. Ian Kelly <ian.g.kelly@gmail.com> - 2012-10-21 12:51 -0600
csiph-web