Re: get each pair from a string.

Discussion in 'Python' started by Emile van Sebille, Oct 22, 2012.

  1. On 10/21/2012 11:51 AM, Ian Kelly wrote:
    > On Sun, Oct 21, 2012 at 12:33 PM, Vincent Davis
    > <> 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
    Emile van Sebille, Oct 22, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Emile van Sebille

    Re: get each pair from a string.

    Emile van Sebille, Oct 22, 2012, in forum: Python
    Replies:
    9
    Views:
    218
    Mark Lawrence
    Oct 24, 2012
  2. Ian Kelly

    Re: get each pair from a string.

    Ian Kelly, Oct 21, 2012, in forum: Python
    Replies:
    0
    Views:
    134
    Ian Kelly
    Oct 21, 2012
  3. Mark Lawrence

    Re: get each pair from a string.

    Mark Lawrence, Oct 21, 2012, in forum: Python
    Replies:
    0
    Views:
    155
    Mark Lawrence
    Oct 21, 2012
  4. Ian Kelly

    Re: get each pair from a string.

    Ian Kelly, Oct 21, 2012, in forum: Python
    Replies:
    0
    Views:
    165
    Ian Kelly
    Oct 21, 2012
  5. Emile van Sebille

    Re: get each pair from a string.

    Emile van Sebille, Oct 22, 2012, in forum: Python
    Replies:
    0
    Views:
    170
    Emile van Sebille
    Oct 22, 2012
Loading...

Share This Page