5.1.4. Nested List Comprehensions

matrix = [
[1, 2, 3, 4] ,
[5, 6, 7, 8] ,
[9, 10, 11, 12] ,
]
For eg. [ [A[i] for A in matrix] for i in range(4) ] #range(4) print from 0 to 3
#[ [1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12] ]

For eg. T = [ ] #struct empty array
for i in range(4): # range(4) print 0 to 3.
T.append( [ A[i] for A in matrix] ) #added each column into T matrix.
#[ [1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12] ]

list( zip (*matrix) ) # if `*` contain and print the column in matrix
#[ (1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12) ]
#if does not `*` contain and print the row in matrix
#[ (1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12) ]
Sign In or Register to comment.