Yoo
Yoo

Reputation: 31

How to iterate for specific elements in a list?

Say I have a large list of tuples, 'a' given as follows:

a = [(0,1,2,3,4,5,6,7,8,9), (10, 11, 12, 13, 14, 15, 16, 17,18,19), (20,21,22,23,24,25,26,27,28) ..... ]

For such a list, how do I make another list by iteration and combine the corresponding elements to get the following:

a = [(0, 10, 20...), (1, 11, 21)....]

Also, lets say I have another list of Arrays,

b = [A, B, C, D, E, F, G ,H, I]

So, how would I combine a and b to make another list c such that:

c = [A(0,10,20), B(1,11,21) ....]

Thanks!

Upvotes: 1

Views: 76

Answers (1)

Kamehameha
Kamehameha

Reputation: 5473

The first a list looks like it's been zipped. You need to unzip it.
Like so -

>>> a = [(0,1,2,3,4,5,6,7,8,9), (10, 11, 12, 13, 14, 15, 16, 17,18,19), (20,21,22,23,24,25,26,27,28)]
>>> zip(*a)
[(0, 10, 20), (1, 11, 21), (2, 12, 22), (3, 13, 23), (4, 14, 24), (5, 15, 25), (6, 16, 26), (7, 17, 27), (8, 18, 28)]

For the second problem, it seem to be the inverse of the first (Assuming that b has 'ABC' as characters).So zip them -

>>> a = zip(*a)
>>> b = "ABCDEFGHI"
>>> zip(b,a)
[('A', (0, 10, 20)), ('B', (1, 11, 21)), ('C', (2, 12, 22)), ('D', (3, 13, 23)), ('E', (4, 14, 24)), ('F', (5, 15, 25)), ('G', (6, 16, 26)), ('H', (7, 17, 27)), ('I', (8, 18, 28))]

EDIT
As suggested by gnibbler in the comments, this method involves upacking of the parameters - (Assuming b as a complex List)

>>> b = [[65, 66], [67, 68], [69, 70], [71, 72], [73, 74], [75, 76], [77, 78], [79, 80], [81, 82]]
>>> zip(b, *a)
[([65, 66], 0, 10, 20), ([67, 68], 1, 11, 21), ([69, 70], 2, 12, 22), ([71, 72], 3, 13, 23), ([73, 74], 4, 14, 24), ([75, 76], 5, 15, 25), ([77, 78], 6, 16, 26), ([79, 80], 7, 17, 27), ([81, 82], 8, 18, 28)]

For more clarity over the difference, here is the example with my earlier answer -

>>> zip(b, zip(*a))
[([65, 66], (0, 10, 20)), ([67, 68], (1, 11, 21)), ([69, 70], (2, 12, 22)), ([71, 72], (3, 13, 23)), ([73, 74], (4, 14, 24)), ([75, 76], (5, 15, 25)), ([77, 78], (6, 16, 26)), ([79, 80], (7, 17, 27)), ([81, 82], (8, 18, 28))]

Upvotes: 2

Related Questions