Python 2.x vs Python 3(三)

Python2.x vs Python3

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():可迭代,不可索引

References

[1] Python dictionary.keys() error

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值