Correcting snippet template
Correcting snippet template for transpose_matrix function. Adding briefly explanation and modifying the code.
This commit is contained in:
committed by
GitHub
parent
db7c1358b3
commit
81d2d7f0b0
@ -3,19 +3,18 @@ title: transpose_matrix
|
|||||||
tags: matrix,list,zip,intermediate
|
tags: matrix,list,zip,intermediate
|
||||||
---
|
---
|
||||||
|
|
||||||
|
Obtaining the transpose of a matrix making use of `zip()` function.
|
||||||
|
|
||||||
Python `zip()` function takes the iterable elements as input and returns the iterator.
|
Python `zip()` function takes the iterable elements as input and returns the iterator.
|
||||||
Since zip funtion returns a `zip object`, we can cast it as list wit `list()`.
|
Since zip funtion returns a `zip object`, we can cast it as list wit `list()`.
|
||||||
```py
|
```py
|
||||||
list(zip([1,2,3],['a','b','c'], [True, False, True]))
|
list(zip([1,2,3],['a','b','c'], [True, False, True])) # [(1, 'a', True), (2, 'b', False), (3, 'c', True)]
|
||||||
# Output: [(1, 'a', True), (2, 'b', False), (3, 'c', True)]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Using `*list`, we can access to each element of the list
|
Using `*list`, we can access to each element of the list
|
||||||
```py
|
```py
|
||||||
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
|
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] # [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
|
||||||
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
|
*[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] # [1, 2, 3] [4, 5, 6] [7, 8, 9] [10, 11, 12]
|
||||||
*[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
|
|
||||||
# Output: [1, 2, 3] [4, 5, 6] [7, 8, 9] [10, 11, 12]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Combining these two elements we can transpose a matrix. We can access to each row of the matrix using the operator `*` to use them as args of `zip()` function.
|
Combining these two elements we can transpose a matrix. We can access to each row of the matrix using the operator `*` to use them as args of `zip()` function.
|
||||||
@ -23,7 +22,8 @@ Combining these two elements we can transpose a matrix. We can access to each ro
|
|||||||
```py
|
```py
|
||||||
def transpose_matrix(l:list):
|
def transpose_matrix(l:list):
|
||||||
return list(zip(*l))
|
return list(zip(*l))
|
||||||
|
```
|
||||||
print(transpose_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]))
|
|
||||||
# Output: [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
|
```py
|
||||||
|
print(transpose_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])) # [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user