1. 程式人生 > 程式設計 >詳解Python3遷移介面變化採坑記

詳解Python3遷移介面變化採坑記

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,3,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.obj) > 0
    def __eq__(self,other.obj) == 0
    def __le__(self,other.obj) <= 0
    def __ge__(self,other.obj) >= 0
    def __ne__(self,other.obj) != 0
  return K

為此,我們需要把程式碼改成:

from functools import cmp_to_key

def comp_two(x,y):
  return y - x

numList = [5,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,4])
print(map_result)    # <map object at 0x000001E553CDC1D0>
print(list(map_result)) # [1,9,16]

# 使用 lambda 匿名函式
print(map(lambda x: x ** 2,4]))  # <map object at 0x000001E553CDC1D0>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。