以下通過程式對迭代方法進行比較,
模組1:mytimer.py
import time
reps=1000
repslist=range(reps)
def timer(func,*pargs,**kargs):
start=time.clock()
for i in repslist:
ret=func(*pargs,**kargs)
elapsed=time.clock()-start
return (elapsed,ret)
time2.py
import sys,mytimer
reps=10000
repslist=range(reps)
def forloop():
res=
for x in repslist:
return res
def listcomp():
return [abs(x) for x in repslist]
#def mapcall(): #只認用於3.0版本。
# return list(map(abs,replist)) #
def genexpr():
return list(abs(x) for x in repslist)
def genfunc():
def gen():
for x in repslist:
yield abs(x)
return list(gen())
print(sys.version)
for test in (forloop,listcomp,genexpr,genfunc):
elapsed,result=mytimer.timer(test)
print '-'*33
print '%-9s:%.5f==>[%s...%s]' % (test.__name__,elapsed,result[0],result[-1])
在2.7版本下
2.7.5 (default, sep 16 2013, 23:16:52) [msc v.1500 32 bit (intel)]
---------------------------------
forloop :1.38339==>[0...9999]
---------------------------------
listcomp :0.70408==>[0...9999]
---------------------------------
genexpr :0.90445==>[0...9999]
---------------------------------
genfunc :0.88582==>[0...9999]
當生成的列表較大時,優勢更加明顯,我這裡將生成999999個元素的列表,
2.7.5 (default, sep 16 2013, 23:16:52) [msc v.1500 32 bit (intel)]
---------------------------------
forloop :147.95689==>[0...999998]
---------------------------------
listcomp :88.12757==>[0...999998]
---------------------------------
genexpr :108.48967==>[0...999998]
---------------------------------
genfunc :105.21874==>[0...999998]
各種排序方法的效能比較
測試環境說明 win xp下,vs2008,主頻 core2 雙核2.53ghz 下面是測試的 using system using system.collections.generic using system.linq using system.text using system.collect...
python對list去重的各種方法
最簡單的思路就是 ids 1,2,3,3,4,2,3,4,5,6,1 news ids forid inids if idnot innews ids news ids.id print news ids這樣也可行,但是看起來不夠爽。另外乙個解決方案就是用set ids 1,4,3,3,4,2,3,...
Object的各種方法
obj.hasownproperty prop 引數 prop 要檢測的屬性字串名稱或者symbol 返回值用來判斷乙個物件是否含有指定的屬性的boolean 所有繼承了object的物件,都會繼承到hasownproperty 方法。這個方法用來檢測乙個物件是否含有特定的自身屬性。和in運算子不同...