enumerate用法和转置矩阵求解、效率测试

enumerate用法和转置矩阵求解、效率测试

枚举函数:
enumerate(iterable[, start]) – > iterator for index, value of iterable
返回一个可迭代对象,将原有可迭代对象的元素和从start开始的数字配对。

练习题:

clipboard

解答:
#方法1,列表扫描追加法
import datetime
matrix = [[1,2,3], [4,5,6]]
tm = []
count = 0
for row in matrix:
for i,col in enumerate(row):
if len(tm) < i + 1: # row有m列,tm就要就要有m行
tm.append([])
tm[i].append(col)
count += 1
print(matrix)
print(tm)
print(count)

#方法2,直接开辟目标空间,矩阵元素交换法(避免引用类型)
matrix = [[1,2,3], [4,5,6]]
tm = [[0 for col in range(len(matrix))] for row in range(len(matrix[0]))]
count = 0
# tm = []
# for row in range(len(matrix[0])):
# tm.append([])
# for col in range(len(matrix)):
# tm[row].append(0)
for i,row in enumerate(tm):
for j,col in enumerate(row):
tm[i][j] = matrix[j][i] #matrix元素搬到tm
count += 1
print(matrix)
print(tm)
print(count)

效率测试:
datetime 或者 %%timeit(Ipython中)

import datetime
matrix = [[1,2,3], [4,5,6], [7,8,9]]
start = datetime.datetime.now()
for c in range(100000):
tm = [] #目标矩阵
for row in matrix:
for i, item in enumerate(row):
if len(tm) < i + 1:
tm.append([])
tm[i].append(item)
delta = (datetime.datetime.now() – start).total_seconds()
print(delta)
print(matrix)
print(tm)

start = datetime.datetime.now()
for c in range(100000):
tm = [0]* len(matrix[0])
for i in range(len(tm)):
tm[i] = [0] * len(matrix)
for i, row in enumerate(tm):
for j, col in enumerate(row):
tm[i][j] = matrix[j][i]
delta = (datetime.datetime.now() – start).total_seconds()
print(delta)
print(matrix)
print(tm)

matrix = [[1,2,3], [4,5,6], [1,2,3], [4, 5, 6],[1,2,3], [4,5,6], [1,2,3], [4, 5, 6],[1,2,3], [4,5,6], [1,2,3], [4, 5, 6],[1,2,3], [4,5,6], [1,2,3], [4, 5, 6],[1,2,3], [4,5,6], [1,2,3], [4, 5, 6],[1,2,3], [4,5,6], [1,2,3], [4, 5, 6],[1,2,3], [4,5,6], [1,2,3], [4, 5, 6],[1,2,3], [4,5,6], [1,2,3], [4, 5, 6],[1,2,3], [4,5,6], [1,2,3], [4, 5, 6]]

clipboard2

4*4开始,先开辟空间效率更高啦!

本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/95539

发表评论

登录后才能评论

联系我们

400-080-6560

在线咨询:点击这里给我发消息

邮件:1823388528@qq.com

工作时间:周一至周五,9:30-18:30,节假日同时也值班