详解Python3迁移接口变化采坑记
2019-10-11 18:07
1606 查看
1、除法相关
在python3之前,
print 13/4 #result=3
然而在这之后,却变了!
print(13 / 4) #result=3.25
"/”符号运算后是正常的运算结果,那么,我们要想只取整数部分怎么办呢?原来在python3之后,“//”有这个功能:
print(13 // 4) #result=3.25
是不是感到很奇怪呢?下面我们再来看一组结果:
print(4 / 13) # result=0.3076923076923077 print(4.0 / 13) # result=0.3076923076923077 print(4 // 13) # result=0 print(4.0 // 13) # result=0.0 print(13 / 4) # result=3.25 print(13.0 / 4) # result=3.25 print(13 // 4) # result=3 print(13.0 // 4) # result=3.0
2、Sort()和Sorted()函数中cmp参数发生了变化(重要)
在python3之前:
def reverse_numeric(x, y): return y - x 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才可以:
def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class K: def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 return K
为此,我们需要把代码改成:
from functools import cmp_to_key def comp_two(x, y): return y - x numList = [5, 2, 4, 1, 3] numList.sort(key=cmp_to_key(comp_two)) print(numList)
这样才能输出结果!
具体可参考链接:Sorting HOW TO
3、map()函数返回值发生了变化
Python 2.x 返回列表,Python 3.x 返回迭代器。要想返回列表,需要进行类型转换!
def square(x): return x ** 2 map_result = map(square, [1, 2, 3, 4]) print(map_result) # <map object at 0x000001E553CDC1D0> print(list(map_result)) # [1, 4, 9, 16] # 使用 lambda 匿名函数 print(map(lambda x: x ** 2, [1, 2, 3, 4])) # <map object at 0x000001E553CDC1D0>
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- python接口自动化(二十三)--unittest断言——上(详解)
- python接口自动化(二十六)--批量执行用例 discover(详解)
- python接口自动化(三十九)- logger 日志 - 上(超详解)
- 对python调用RPC接口的实例详解
- python接口自动化(四十)- logger 日志 - 下(超详解)
- python接口自动化(三十二)--Python发送邮件(常见四种邮件内容)番外篇——上(详解)
- python接口自动化(九)--python中字典和json的区别(详解)
- 详解Python 3.1新变化之核心语言篇
- python接口自动化(二十四)--unittest断言——中(详解)
- python接口自动化(十四)--session关联接口(详解)
- python接口自动化(三十七)-封装与调用--读取excel 数据(详解)
- 详解Python程序与服务器连接的WSGI接口
- python接口自动化(十九)--Json 数据处理---实战(详解)
- python接口自动化(四)--接口测试工具介绍(详解)
- python接口自动化(三十八)-python操作mysql数据库(详解)
- python接口自动化(三十)--html测试报告通过邮件发出去——中(详解)
- python接口自动化(二十五)--unittest断言——下(详解)
- python接口自动化(二十六)--批量执行用例 discover(详解)
- python接口自动化(八)--发送post请求的接口(详解)
- python接口自动化(三十四)-封装与调用--函数和参数化(详解)