Python中Range和XRange的區(qū)別(Difference between Range and XRange in Python)最近機(jī)器出了點(diǎn)問(wèn)題,所以一直沒(méi)有寫(xiě)新的東西出來(lái)。之前在讀Python的代碼的時(shí)候,發(fā)覺(jué)好多人喜歡用XRange,而不是Range,我也只是記得學(xué)習(xí)的時(shí)候開(kāi)始學(xué)到的是Range,后面又看到有個(gè)XRange,當(dāng)時(shí)也沒(méi)有深究,為什么Python里面要有兩個(gè)同樣的功能的系統(tǒng)函數(shù)。今天再去仔細(xì)查了下文檔,原來(lái)它們之間還是有點(diǎn)區(qū)別,雖然不是很大,但至少XRange的效率會(huì)比Range的高。在文檔中是這樣寫(xiě)的: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的方法中,它會(huì)生成一個(gè)list的對(duì)象,但是在XRange中,它生成的卻是一個(gè)xrange的對(duì)象,當(dāng)返回的東西不是很大的時(shí)候,或者在一個(gè)循環(huán)里,基本上都是從頭查到底的情況下,這兩個(gè)方法的效率差不多。但是,當(dāng)返回的東西很大,或者循環(huán)中常常會(huì)被Break出來(lái)的話,還是建議使用XRange,這樣既省空間,又會(huì)提高效率。
下面舉個(gè)例子:
如果使用range函數(shù),執(zhí)行下面的語(yǔ)句,將會(huì)得到后面的結(jié)果:
>>> 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 但是,將開(kāi)始的range用xrange替換,將會(huì)得到不同的結(jié)果:
>>> a = xrange(0,100)>>> print type(a)>>> print axrange(100)>>> print a[0], a[1]0 1
這里可以很直接的看到它們的不同點(diǎn),雖然a[0], a[1]返回的值是相同的。所以,以后coding的時(shí)候還是盡可能使用xrange了
本文來(lái)自ChinaUnix博客,如果查看原文請(qǐng)點(diǎn):http://blog.chinaunix.net/u3/93014/showart_2177334.html |