笨办法
# TODO 计算矩阵的转置
def transpose(M):
result = []
for j in range(len(M[0])):
row = []
for i in range(len(M)):
row.append(M[i][j])
result.append(row)
return result
优化后
# TODO 计算矩阵的转置
def transpose(M):
return [list(row) for row in zip(*M)]
B = [[1,2,3,5],
[2,3,3,5],
[1,2,5,1]]
print B
print zip(*B)
print transpose(B)
[[1, 2, 3, 5], [2, 3, 3, 5], [1, 2, 5, 1]]
[(1, 2, 1), (2, 3, 2), (3, 3, 5), (5, 5, 1)]
[[1, 2, 1], [2, 3, 2], [3, 3, 5], [5, 5, 1]]
* args和** kwargs是一个常见的习惯用法,它允许任意数量的函数参数,
* args会给你所有的元组参数:
def foo(*args):
for a in args:
print a
foo(1)
1
foo(1,2,3
1
2
3
** kwargs会给你所有的关键字参数,对那些对应于形式参数的字典。
def bar(**kwargs):
for a in kwargs:
print a, kwargs[a]
bar(name = 'one', age = 27)
age 27
name one
def foo(param1, *param2):
print param1
print param2
def bar(param1, **param2):
print param1
print param2
foo(1,2,3,4)
bar(1,a=2,b=3)
1
(2, 3, 4)
1
{'a': 2, 'b': 3}
参考链接点击打开链接