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类),是一个生成器,具有列表的某些属性,比如实现了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