566. 重塑矩阵
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
if len(mat) * len(mat[0]) != r * c:
return mat
result = []
row = []
for words in mat:
for word in words:
row.append(word)
if len(row) == c:
result.append(row)
row = []
return result
118. 杨辉三角
杨辉三角,用上一行错位相加得到下一行
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0: return []
res = [[1]]
while len(res) < numRows:
newRow = [a+b for a, b in zip([0]+res[-1], res[-1]+[0])]
res.append(newRow)
return res
zip()函数示例
m = [[1,2,3], [4,5,6], [7,8,9]]
n = [[2,2,2], [3,3,3], [4,4,4]]
list(zip(m))
输出:
[([1, 2, 3],), ([4, 5, 6],), ([7, 8, 9],)]
m = [[1,2,3], [4,5,6], [7,8,9]]
n = [[2,2,2], [3,3,3], [4,4,4]]
list(zip(m,n))
输出:
[([1, 2, 3], [2, 2, 2]), ([4, 5, 6], [3, 3, 3]), ([7, 8, 9], [4, 4, 4])]