歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python中Range和XRange的區別

Python中Range和XRange的區別

日期:2017/3/1 10:49:33   编辑:Linux編程

Python中Range和XRange的區別(Difference between Range and XRange in Python)

最近機器出了點問題,所以一直沒有寫新的東西出來。之前在讀Python的代碼的時候,發覺好多人喜歡用XRange,而不是Range,我也只是 記得學習的時候開始學到的是Range,後面又看到有個XRange,當時也沒有深究,為什麼Python裡面要有兩個同樣的功能的系統函數。今天再去仔 細查了下文檔,原來它們之間還是有點區別,雖然不是很大,但至少XRange的效率會比Range的高。

在文檔中是這樣寫的:xrange([start,] stop[, step])This function is very similar to range(), but returns an ``xrange object'' instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range's elements are never used (such as when the loop is usually terminated with break).Note: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs ("short" Python integers), and also requires that the number of elements fit in a native C long.
在Range的方法中,它會生成一個list的對象,但是在XRange中,它生成的卻是一個 xrange的對象,當返回的東西不是很大的時候,或者在一個循環裡,基本上都是從頭查到底的情況下,這兩個方法的效率差不多。但是,當返回的東西很大, 或者循環中常常會被Break出來的話,還是建議使用XRange,這樣既省空間,又會提高效率。
下面舉個例子:
如果使用range函數,執行下面的語句,將會得到後面的結果:
>>> a = range(0,100)

>>> print type(a)

>>> print a

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

>>> print a[0], a[1]

0 1

但是,將開始的range用xrange替換,將會得到不同的結果:
>>> a = xrange(0,100)

>>> print type(a)

>>> print axrange(100)

>>> print a[0], a[1]

0 1

這裡可以很直接的看到它們的不同點,雖然a[0], a[1]返回的值是相同的。所以,以後coding的時候還是盡可能使用xrange了

Copyright © Linux教程網 All Rights Reserved