題目地址:https://leetcode.com/problems/transpose-matrix/description/
大意:將矩陣的行列轉(zhuǎn)換师幕。
思路: 1.簡單的循環(huán)操作 2.python 的zip()
方法 3.numpy庫
class Solution:
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
return list(map(list, zip(*A)))
def transpose2(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
rows, cols = len(A), len(A[0])
res = [[0] * rows for _ in range(cols)]
for row in range(rows):
for col in range(cols):
res[col][row] = A[row][col]
return res
def transpose3(self,A):
return np.array(A).T.tolist()
知識點(diǎn):
-
zip()
方法的使用:zip([iterable, ...])
zip()是Python的一個(gè)內(nèi)建函數(shù)蛉鹿,它接受一系列可迭代的對象作為參數(shù)煌集,將對象中對應(yīng)的元素打包成一個(gè)個(gè)tuple(元組)述雾,然后返回由這些tuples組成的list(列表)褪猛。若傳入?yún)?shù)的長度不等,則返回list的長度和參數(shù)中長度最短的對象相同豫柬。利用*號操作符锌钮,可以將list unzip解壓:
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b)
[(1, 4), (2, 5), (3, 6)]
zip(a,c)
[(1, 4), (2, 5), (3, 6)]
zip(*zipped)
[(1, 2, 3), (4, 5, 6)]
- map()方法的使用:
list = map(func, iter)
其中桥温, func是函數(shù), iter是可迭代的序列梁丘。
它的功能是:將一個(gè)序列中的每一個(gè)元素應(yīng)用傳入的函數(shù)侵浸, 并返回一個(gè)包含所有函數(shù)調(diào)用結(jié)果的一個(gè)列表.
特別注意的是,python3中返回的是一個(gè)對象氛谜,轉(zhuǎn)換成函數(shù)得用list()
方法
3.numpy 庫掏觉,.T
就是二維矩陣的轉(zhuǎn)置,跟上學(xué)學(xué)的一樣值漫。 把原生list轉(zhuǎn)成numpy的array后澳腹,再轉(zhuǎn)回來就行了。