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.www58058.com/95539

(0)
JacoJaco
上一篇 2018-04-08 21:08
下一篇 2018-04-08 21:20

相關推薦

  • 內置數據結構

    list,tuple,str,bytes,bytearray,set,切片,分裝解構,冒泡法

    2018-03-31
  • Python 部分知識點總結(七)

    此篇博客只是記錄第九周未掌握或不熟悉的知識點,用來加深印象。

    Python筆記 2018-05-06
  • Python函數

    函數 數學函數 Python函數 若干語句塊、函數名稱、參數列表構成,組織代碼的最小單元 完成一定的功能 作用 結構化編程對代碼的最基本的封裝,一般按照功能組織一段代碼 復用,減少冗余代碼 簡潔美觀,可讀易懂 函數分類 內建函數,max()、reversed() 庫函數,math.ceil() 函數定義、調用 def語句定義函數 def 函數名(參數列表):…

    2018-04-16
  • python summary(for previous 6 weeks)

    Meghan(haven’t been fullly organized)

    2018-04-19
  • Python函數返回值、作用域以及樹的概念

    Python函數返回值、作用域以及樹的概念

    Python筆記 2018-04-15
  • Python內置數據結構——字符串

    知識結構圖 學習筆記 字符串 字符組成的有序序列,字符的集合 使用單引號、雙引號、三引號引起來的字符序列 不可變對象 Unicode類型 定義 單引號、雙引號、三引號 r、R:引號內的字符原樣輸出 元素訪問 索引訪問 可迭代 join連接 “string“.join(iteratable) 使用string作為分隔符將可迭代對象連接起…

    2018-03-31
欧美性久久久久