经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python3 » 查看文章
详解Python3迁移接口变化采坑记
来源:jb51  时间:2019/10/12 9:03:34  对本文有异议

1、除法相关

在python3之前,

  1. print 13/4 #result=3

然而在这之后,却变了!

  1. print(13 / 4) #result=3.25

"/”符号运算后是正常的运算结果,那么,我们要想只取整数部分怎么办呢?原来在python3之后,“//”有这个功能:

  1. print(13 // 4) #result=3.25

是不是感到很奇怪呢?下面我们再来看一组结果:

  1. print(4 / 13) # result=0.3076923076923077
  2. print(4.0 / 13) # result=0.3076923076923077
  3. print(4 // 13) # result=0
  4. print(4.0 // 13) # result=0.0
  5. print(13 / 4) # result=3.25
  6. print(13.0 / 4) # result=3.25
  7. print(13 // 4) # result=3
  8. print(13.0 // 4) # result=3.0

2、Sort()和Sorted()函数中cmp参数发生了变化(重要)

在python3之前:

  1. def reverse_numeric(x, y):
  2. return y - x
  3. print sorted([5, 2, 4, 1, 3], cmp=reverse_numeric)

输出的结果是:[5, 4, 3, 2, 1]

但是在python3中,如果继续使用上面代码,则会报如下错误:

TypeError: 'cmp' is an invalid keyword argument for this function

咦?根据报错,意思是在这个函数中cmp不是一个合法的参数?为什么呢?查阅文档才发现,在python3中,需要把cmp转化为一个key才可以:

  1. def cmp_to_key(mycmp):
  2. 'Convert a cmp= function into a key= function'
  3. class K:
  4. def __init__(self, obj, *args):
  5. self.obj = obj
  6. def __lt__(self, other):
  7. return mycmp(self.obj, other.obj) < 0
  8. def __gt__(self, other):
  9. return mycmp(self.obj, other.obj) > 0
  10. def __eq__(self, other):
  11. return mycmp(self.obj, other.obj) == 0
  12. def __le__(self, other):
  13. return mycmp(self.obj, other.obj) <= 0
  14. def __ge__(self, other):
  15. return mycmp(self.obj, other.obj) >= 0
  16. def __ne__(self, other):
  17. return mycmp(self.obj, other.obj) != 0
  18. return K

为此,我们需要把代码改成:

  1. from functools import cmp_to_key
  2.  
  3. def comp_two(x, y):
  4. return y - x
  5.  
  6. numList = [5, 2, 4, 1, 3]
  7. numList.sort(key=cmp_to_key(comp_two))
  8. print(numList)

这样才能输出结果!

具体可参考链接:Sorting HOW TO

3、map()函数返回值发生了变化

Python 2.x 返回列表,Python 3.x 返回迭代器。要想返回列表,需要进行类型转换!

  1. def square(x):
  2. return x ** 2
  3.  
  4. map_result = map(square, [1, 2, 3, 4])
  5. print(map_result) # <map object at 0x000001E553CDC1D0>
  6. print(list(map_result)) # [1, 4, 9, 16]
  7.  
  8. # 使用 lambda 匿名函数
  9. print(map(lambda x: x ** 2, [1, 2, 3, 4])) # <map object at 0x000001E553CDC1D0>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号