Assign a list correctly

This MWE re-massaging MWE 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 as follows:

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

Ie, 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 slightly larger list a , is there a more efficient way to do this?

+4
source share
1 answer

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 several sequences as arguments and combines the elements from each to form new lists. Moving to a with the * splat argument, we ask Python to expand a into separate arguments on zip() .

Note that at the output you get a list of tuples; return list items to lists as needed:

 b = map(list, zip(*a)) 
+14
source

Source: https://habr.com/ru/post/1492105/


All Articles