## Python3迁移接口变化采坑记

qinjianhuang 2020-11-13 05:22:52
Python python3 接口 迁移 变化

1、除法相关

``````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参数发生了变化（重要）

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

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

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

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

https://huangqinjian.blog.csdn.net/article/details/79618263