range 直接回傳list
range(start, stop[, step]) 到stop結束,但不包含stop
length = len() #假設是5
range(0, length)
# [0,1,2,3,4]
# 反過來就要
range(length-1, -1 , -1)
# [4,3,2,1,0]
xrange是generator
一次只回傳一個
for loop的話xrange會比range效能好,因為xrange不用allocate array
目前python3的range就是python2的xrange
如果要return list就要
list(xrange(0, length))
實測python2
python -m timeit 'for i in range(1000000):' ' pass'
# 10 loops, best of 3: 18.5 msec per loop
python -m timeit 'for i in xrange(1000000):' ' pass'
# 100 loops, best of 3: 11.1 msec per loop
但在python3
python -m timeit 'for i in range(1000000):' ' pass'
# 10 loops, best of 3: 24.1 msec per loop
這就跟complier有關了
另外python3 range跟enumerate比較,range速度快一點,大概是因為enumerate有key跟value
但是如果是同時要idx value還是enumerate快點?
test = list(range(0, 200))
# only take value
# 2.674504293128848
for i in test:
print(i)
# get idx and value
# 6.778496273094788
for i in range(0, len(test)):
print(test[i])
# get key
# 3.3357064370065928
for i in range(0, len(test)):
print(i)
# get idx and value
# 5.7636028518900275
for k, v in enumreate(test):
print(v)
刷leetcode的時候,重要的是complexity,剩下的是減少判斷
至於while比for loop慢請看這