Python3 Python2 差異

1. 生成器

python2.7
a = (x for x in xrange(10))
a.next()
python3
a = (x for x in range(10))
next(a)

2. range xrange

python2.7
  • python2中 xrange返回生成器(xrange類, 類似/相同python3的range類)
  • range返回一個列表
In [1]: a = range(10)
In [2]: a
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]: a?

Type:        list
String form: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Length:      10
Docstring:
list() -> new empty list
list(iterable) -> new list initialized from iterable's items

----------------------------------------------------------
In [6]: b = xrange(10)
In [7]: b
Out[7]: xrange(10)
In [8]: b?

Type:        xrange
String form: xrange(10)
Length:      10
Docstring:
xrange(stop) -> xrange object
xrange(start, stop[, step]) -> xrange object

Like range(), but instead of returning a list, returns an object that
generates the numbers in the range on demand.  For looping, this is
slightly faster than range() and more memory efficient.
python3
  • python3 中,沒有xrange
  • range返回range類(類似/相同python2的xrange類),是一個生成器,具有列表的某些屬性,比如實現(xiàn)了len(self),可直接訪問下標
In [1]: a = xrange(10)
NameError                                 Traceback (most recent call last)
<ipython-input-1-192c1c141dd2> in <module>()
----> 1 a = xrange(10)
NameError: name 'xrange' is not defined

---------------------------------------------------------------------------
In [2]: b = range(10)
In [3]: b
Out[3]: range(0, 10)
In [4]: b?

Type:        range
String form: range(0, 10)
Length:      10
Docstring:
range(stop) -> range object
range(start, stop[, step]) -> range object

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 step is given, it specifies the increment (or decrement).

In [5]: len(b)
Out[5]: 10
In [12]: int(b.__len__())
Out[12]: 10
In [13]: b[8]
Out[13]: 8

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

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

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