Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re assign a list efficiently

This is a MWE of the re-arrainging I need to do:

a = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
b = [[], [], []]

for item in a:
    b[0].append(item[0])    
    b[1].append(item[1])
    b[2].append(item[2])

which makes b lool like this:

b = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]

I.e., every first item in every list inside a will be stored in the first list in b and the same for lists two and three in b.

I need to apply this to a somewhat big a list, is there a more efficient way to do this?

like image 937
Gabriel Avatar asked Dec 09 '22 14:12

Gabriel


1 Answers

There is a much better way to transpose your rows and columns:

b = zip(*a)

Demo:

>>> a = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
>>> zip(*a)
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]

zip() takes multiple sequences as arguments and pairs up elements from each to form new lists. By passing in a with the * splat argument, we ask Python to expand a into separate arguments to zip().

Note that the output gives you a list of tuples; map elements back to lists as needed:

b = map(list, zip(*a))
like image 52
Martijn Pieters Avatar answered Dec 27 '22 13:12

Martijn Pieters