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!!

6
  • Possible duplicate of Pairs from single list Commented Apr 10, 2017 at 15:13
  • Sorry, marked the wrong question as duplicate, but if you search there are a few matching. Commented Apr 10, 2017 at 15:15
  • What should be the last tuple in the list? Commented Apr 10, 2017 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? Commented Apr 10, 2017 at 15:23
  • @EricDuminil in this case the last tuple would be ('c','f'). Commented Apr 10, 2017 at 16:09

3 Answers 3

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')]
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.
1
b = [(a[i][0], a[i+1][1]) for i in range(len(a)-1)]

Comments

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'),...]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.