2

I am having problems iterating in python. I have this structure:

a = [('f', 'f'),
 ('a', 'a'),
 ('e', 'e'),
 ('d', 'd'),
 ('e', 'e'),
 ('d', 'd'),
 ('b', 'b'),
 ('e', 'e'),
 ('d', 'd'),
 ('b', 'b'),
 ('a', 'a'),
 ('b', 'b'),
 ('g', 'g'),
 ('h', 'h'),
 ('c', 'c'),
 ('h', 'h'),
 ('a', 'a'),
 ('c', 'c'),
 ('g', 'g'),
 ('h', 'h'),
 ('g', 'g'),
 ('c', 'c'),
 ('f', 'f')]

And from that I want to get an output that gives me the first value of a parenthesis with the value of the next parenthesis, something like this:

b = [('f','a'), ('a','e'), ('e','d')etc..]

Thank you very much!!

  • Possible duplicate of [Pairs from single list](http://stackoverflow.com/questions/4628290/pairs-from-single-list) – Peter Wood Apr 10 '17 at 15:13
  • Sorry, marked the wrong question as duplicate, but if you search there are a few matching. – Peter Wood Apr 10 '17 at 15:15
  • What should be the last tuple in the list? – Eric Duminil Apr 10 '17 at 15:17
  • @Mee: what if the tuple contains different elements for the first and second item, so `[('a','b'),('a','c'),...]` what is the expected output in that case? – Willem Van Onsem Apr 10 '17 at 15:23
  • @EricDuminil in this case the last tuple would be ('c','f'). –  Apr 10 '17 at 16:09
  • @WillemVanOnsem Well, with the input i am working with that is not gonna happen. But let's suppose I want that the loop gives me the first value of a parenthesis with the first value of the next parenthesis, the expected output in that case would be ('a','a') –  Apr 10 '17 at 16:13

3 Answers3

4

Simply use some list comprehension:

[(x[0],y[0]) for x,y in zip(a,a[1:])]

Or even more elegantly:

[(x,y) for (x,_a),(y,_b) in zip(a,a[1:])]

You can avoid making a copy with the slicing, by using islice from itertools:

from itertools import islice

[(x,y) for (x,_a),(y,_b) in zip(a,islice(a,1,None))]

These all give:

>>> [(x,y) for (x,_a),(y,_b) in zip(a,a[1:])]
[('f', 'a'), ('a', 'e'), ('e', 'd'), ('d', 'e'), ('e', 'd'), ('d', 'b'), ('b', 'e'), ('e', 'd'), ('d', 'b'), ('b', 'a'), ('a', 'b'), ('b', 'g'), ('g', 'h'), ('h', 'c'), ('c', 'h'), ('h', 'a'), ('a', 'c'), ('c', 'g'), ('g', 'h'), ('h', 'g'), ('g', 'c'), ('c', 'f')]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Since the pairs always have the same two elements in the example, I'm not sure which elements should be picked in each tuple, and if they're really always the same in the input list. – Eric Duminil Apr 10 '17 at 15:19
  • @EricDuminil: As far as I know it is was in the body of the question, but somehow either my memory is failing, or the question has been edited immediately after posting. – Willem Van Onsem Apr 10 '17 at 15:20
1
b = [(a[i][0], a[i+1][1]) for i in range(len(a)-1)]
francisco sollima
  • 7,952
  • 4
  • 22
  • 38
1

you may try this one

map(lambda x, y: (x[0], y[0]), a[:-1], a[1:])

output:

[('f', 'a'),('a', 'e'),('e', 'd'),('d', 'e'),...]
Deba
  • 609
  • 8
  • 17