Python3 Python2 差异

2018-09-03  本文已影响0人  小淼不卖萌

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
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
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

上一篇下一篇

猜你喜欢

热点阅读