python的range函數(shù)看似簡(jiǎn)單

當(dāng)我們?cè)谘h(huán)中用到for或者while針對(duì)一段數(shù)字進(jìn)行循環(huán)的時(shí)候,我們其實(shí)是可以直接表達(dá)其范圍的,但是為啥python還是要引入range函數(shù)呢?

作為python的內(nèi)置函數(shù),個(gè)人推測(cè)range是在其他內(nèi)置函數(shù)中需要用到list的index時(shí)候需要的,所以可以看到range函數(shù)的定義:

Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When a step is given, it specifies the increment (or decrement).

包含開(kāi)始數(shù)字,而將停止的數(shù)字排除在外,比如range(5):

range(5)

有意思的是,這是python3的range函數(shù),而python2的xrange函數(shù)反而是更加高速和占用較小內(nèi)存的。

可以利用python的內(nèi)嵌函數(shù)timeit 與 sys.getsizeof 進(jìn)行測(cè)試:

python -m timeit 'for i in range(1000000):' ' pass'

10 loops, best of 3: 90.5 msec per loop

# testing xrange()

python -m timeit 'for i in xrange(1000000):' ' pass'

10 loops, best of 3: 51.1 msec per loop

--------------------------------------------

xr = xrange(1, 10000)

r = range(1, 10000)

size_xr = sys.getsizeof(xr)

size_r = sys.getsizeof(r)

print(f"The xrange() function uses {size_xr} bytes of memory.")

print(f"The range() function uses {size_r} bytes of memory.")

輸出是:

The xrange() function uses 24 bytes of memory.

The xrange() function uses 80064 of memory.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容