天天看點

python四種清單的插入方法及其效率此篇部落格是此時清單中各種方法添加資料時的效率問題,如有錯誤之處,望大家指出!coding:utf-8append花費的時間是 0.008006025272567989extend花費的時間為 0.010472806737249051insert花費的時間為 0.012643240513279762plus花費的時間為 13.00245008582025由此可得append是耗時最短的

此篇部落格是此時清單中各種方法添加資料時的效率問題,如有錯誤之處,望大家指出!

coding:utf-8

from timeit import timeit

def count_append():

lists = []

for x in range(0, 100000):

lists.append(x)

cost_time = timeit(stmt=count_append, number=1)

print("append花費的時間是", cost_time)

def count_extend():

lists = []

for x in range(0, 100000):

list1 = [x]

lists.extend(list1)

cost_time = timeit(stmt=count_extend, number=1)

print("extend花費的時間為", cost_time)

def count_insert():

lists = []

for x in range(0, 100000):

lists.insert(x, x)

cost_time = timeit(stmt=count_insert, number=1)

print("insert花費的時間為", cost_time)

def count_plus():

lists = []

for x in range(0, 100000):

list1 = [x]

lists = lists+list1

cost_time = timeit(stmt=count_plus, number=1)

print("plus花費的時間為", cost_time)

append花費的時間是 0.008006025272567989

extend花費的時間為 0.010472806737249051

insert花費的時間為 0.012643240513279762

plus花費的時間為 13.00245008582025

由此可得append是耗時最短的