## Mining pit record of python3 migration interface change

qinjianhuang 2020-11-13 05:22:52
mining pit record python3 python

1、 Division correlation

stay python3 Before ,

``````print 13/4 #result=3
``````

But after that , But it changed ！

``````print(13 / 4) #result=3.25
``````

"/” After symbol operation, it is the normal result of operation , that , What if we want to take only the integral part ？ Originally in python3 after ,“//” It has this function ：

``````print(13 // 4) #result=3.25
``````

Isn't it strange ？ Let's look at another set of results ：

``````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（） and Sorted（） Function cmp The parameters have changed （ important ）

stay python3 Before ：

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

The output is zero ：[5, 4, 3, 2, 1]

But in python3 in , If you continue to use the code above , The following error will be reported ：

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

Why ？ According to the report , It means in this function cmp Not a valid parameter ？ Why? ？ Look up the document and find out , stay python3 in , Need to put cmp Turn into a key Can only be ：

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

So , We need to change the code to ：

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

So that we can output the result ！

3、map() The return value of the function has changed

Python 2.x return list ,Python 3.x return iterator . To return to the list , Type conversion required ！

``````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]
# Use lambda Anonymous functions
print(map(lambda x: x ** 2, [1, 2, 3, 4])) # <map object at 0x000001E553CDC1D0>
``````