2

So I have a question, I have an iterable (string or list here) like string = "ABCDEFG" and I want to ouput something like

A-B
B-C
C-D
...
F-G

So I know this works (forgot to handle indexError, but whatever) but it's pretty ugly...

for i in range(len(myString)):
    element1 = myString[i]
    element2 = myString[i+1]
    print("theshit")

Is there a way of doing that in a more elegant/pythonic way ? I think itertools can be a solution but I don't know how it works..

By the way, I need myString only for this loop so maybe generators (don't know how to use that too, I'm still learning)

Thanks :)

BobLeGob
  • 181
  • 1
  • 1
  • 5
  • If ```inp = 'ABCDEFG'``` then maybe something like: ```list = ['%s-%s' %(inp[i],inp[i+1]) for i in range(len(inp)-1)]``` would work for you? – Xirtaminu Apr 01 '16 at 14:38
  • 1
    you *could* do `element1, element2 = myString[i:i+2]` – Wayne Werner Apr 01 '16 at 14:39
  • @M.Massias I'd probably re-add the link as a comment, just mention that it's helpful if you want to do things the other way. I suspect someone will stumble on this question needing to do things the other way :) (and vice versa?) – Wayne Werner Apr 01 '16 at 14:45
  • Not exactly the same question, but still might be interesting: http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks – P. Camilleri Apr 01 '16 at 14:46

3 Answers3

5

itertools.izip might be useful here if you zip your sequence with the tail of the sequence (which you can get using itertools.islice):

>>> from itertools import islice, izip
>>> iterable = "abcdefg"
>>> for x in izip(iterable, islice(iterable, 1, None)): print x
...
('a', 'b')
('b', 'c')
('c', 'd')
('d', 'e')
('e', 'f')
('f', 'g')
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
4

itertools has the following recipe that does exactly what you need:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)
chapelo
  • 2,519
  • 13
  • 19
1

Here is one option, but Frenrich's answer is definitely the best.

I only mention it because it may be helpful in a similar sort of situation.

sequence = 'ABCDEFG'
iter_1 = iter(sequence)
iter_2 = iter(sequence)

next(iter_2) # throw away the first value

for a, b in zip(iter_1, iter_2):
    print(a, b)
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290