Python2.x vs Python3——从 raw_input() 到 input()
int/long
在 Python 2.x 视 int/long 为不同的整型类型,在 Python 3中不再进行区分,Python 2.x 还是 Python 3 都对浮点数的单精度(float)和双精度(double)进行区分,均视为双精度类型,也即在 Python 3 中实现了整型/长整型,单精度/双精度的统一。
# Python 2.x
>>> a = 10
>>> type(a)
<type 'int'>
>>> a = 10l
>>> type(a)
<type 'long'>
cmp 参数
在 Python 3.x 的世界里,一些函数(sorted、min、max)不再支持 cmp 参数(用于对大小的定义)。
next() ⇒ __next__()
In Python 3, to make syntax more consistent, the next() method was renamed to __next__().
dict.keys()
TypeError: ‘dict_keys’ object does not support indexing
>>> d = {'video':0, 'music':23}
>>> k = b.keys()
>>> k[0]
TypeError: 'dict_keys' object does not support indexing
>>> k
dict_keys(['music', 'video'])
Python 3 改变了 dict.keys() 的行为,在 Python 3 中它返回一个 dict_keys 类型对象,可迭代但不可索引(iterable but not indexable,就像 Python 2. 中的 dict.iterkeys()),可通过显式地调用 list 实现类型的转换。
如下代码所示:
>>> b = { 'video':0, 'music':23 }
>>> k = list(b.keys())
>>> k
['music', 'video']
或者:
>>> list(b)
['music', 'video']
(1)xrange,range(Python 2) ⇒ range(Python 3)
Python 2:**xrange:可迭代,不可索引;**range:可迭代,可索引
Python 3:range:可迭代,不可索引(2)dict.keys(),dict.getkeys()(Python 2) ⇒ dict.keys()(Python 3)
Python 2:dict.keys():可迭代,可索引;dict.getkeys():可迭代,不可索引
Python 3:dict.keys():可迭代,不可索引