I'm thinking of reading Deep Learning Book, but I get sleepy when I just read the letters, so I tried to deepen my understanding while implementing the items that came out with python. think. I don't know if there is demand, but I'm thinking of making it into a series (laughs). This time it is transposed. Recently, I've forgotten python only in c ++ and c, so I'll implement it in python as a review. ** Addendum: I tried to make it into a series (laughs). The table of contents is here. ** **
The definition of the book (page 24) says that it is a mirror image of the diagonal of the matrix, called the main diagonal, starting from the upper left corner to the lower right. For more information, please visit here.
The easy way is to use numpy. I referred to here.
main.py
import numpy
def main():
l_2d = [[0, 1, 2], [3, 4, 5]]
arr_t = np.array(l_2d).T.tolist()
print(l_2d)
# [[0 3]
# [1 4]
# [2 5]]
** Addendum: ** Click here for other transposition methods commented by @shiracamus
>>> l_2d = [[0, 1, 2], [3, 4, 5]]
>>> [*zip(*l_2d)]
[(0, 3), (1, 4), (2, 5)]
>>> list(map(list, zip(*l_2d)))
[[0, 3], [1, 4], [2, 5]]
>>> [[*row] for row in zip(*l_2d)]
[[0, 3], [1, 4], [2, 5]]
>>> [list(row) for row in zip(*l_2d)]
[[0, 3], [1, 4], [2, 5]]
If you use the above method, it will be an instant kill, but I will try to make it myself. The idea is to first combine the elements of each array in the array (0 and 3 in the example above) into a single array and add it as the first element of a new 2D array. I tried this this time with the image of doing the same thing with 1 and 4, 2 and 5. I just implemented it as I came up with it, so please let me know if there is a better way. The implementation looks like this.
main.py
def transpose(arr):
col = len(arr[0]) #In this case 3
row = len(arr) #2 in this case
ans_list = []
i = 0
while i < col:
tmp_list = []
j = 0
while j < row:
tmp_list.append(arr[j][i])
j += 1
ans_list.append(tmp_list)
i += 1
return ans_list
def main():
l_2d = [[0, 1, 2], [3, 4, 5]]
print(transpose(l_2d))
# [[0 3]
# [1 4]
# [2 5]]
** Addendum: ** Click here for how to use the for statement, which was commented by @shiracamus.
def transpose(arr):
col = len(arr[0]) #In this case 3
row = len(arr) #2 in this case
rows = []
for c in range(col):
cols = []
for r in range(row):
cols.append(arr[r][c])
rows.append(cols)
return rows
I'm going to read a book on deep learning loosely like this.
Recommended Posts