How to transpose a 2D list array using loops in python? -


say = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]] , want transpose = [[1,0,4], [1,2,0], [1,-1,10], [6,3,42]] using loops in python. current code have is:

def transpose(a):     s = []     row in range(len(a)):         col in range(len(a)):             s = s + [a[col][row]] return s 

but gives me output of:

[1, 0, 4, 1, 2, 0, 1, -1, 10] 

instead of this:

[[1,0,4], [1,2,0], [1,-1,10], [6,3,42]] 

can me? i'm still new @ stuff , don't understand why doesn't work. much!

use zip()

>>> = [[1, 1, 1, 6], [0, 2, -1, 3], [4, 0, 10, 42]] >>> [list(x) x in zip(*a)] [[1, 0, 4], [1, 2, 0], [1, -1, 10], [6, 3, 42]] 

zip(*a) unpacks 3 sub-lists in a , combines them element element. meaning, first elements of each of 3 sub-lists combined together, second elements combined , on. zip() returns tuples instead of lists want in output. this:

>>> zip(*a) [(1, 0, 4), (1, 2, 0), (1, -1, 10), (6, 3, 42)] 

[list(x) x in zip(*a)] converts each of tuples lists giving output way need it.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -