最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Python3遷移接口變化采坑記

 更新時(shí)間:2019年10月11日 10:23:27   作者:qinjianhuang  
這篇文章主要介紹了詳解Python3遷移接口變化采坑記,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1、除法相關(guān)

在python3之前,

print 13/4  #result=3

然而在這之后,卻變了!

print(13 / 4) #result=3.25

"/”符號(hào)運(yùn)算后是正常的運(yùn)算結(jié)果,那么,我們要想只取整數(shù)部分怎么辦呢?原來在python3之后,“//”有這個(gè)功能:

print(13 // 4) #result=3.25

是不是感到很奇怪呢?下面我們?cè)賮砜匆唤M結(jié)果:

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()函數(shù)中cmp參數(shù)發(fā)生了變化(重要)

在python3之前:

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

輸出的結(jié)果是:[5, 4, 3, 2, 1]

但是在python3中,如果繼續(xù)使用上面代碼,則會(huì)報(bào)如下錯(cuò)誤:

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

咦?根據(jù)報(bào)錯(cuò),意思是在這個(gè)函數(shù)中cmp不是一個(gè)合法的參數(shù)?為什么呢?查閱文檔才發(fā)現(xiàn),在python3中,需要把cmp轉(zhuǎn)化為一個(gè)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)

這樣才能輸出結(jié)果!

具體可參考鏈接:Sorting HOW TO

3、map()函數(shù)返回值發(fā)生了變化

Python 2.x 返回列表,Python 3.x 返回迭代器。要想返回列表,需要進(jìn)行類型轉(zhuǎn)換!

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 匿名函數(shù)
print(map(lambda x: x ** 2, [1, 2, 3, 4]))  # <map object at 0x000001E553CDC1D0>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

综艺| 萨迦县| 眉山市| 祁连县| 临武县| 阿巴嘎旗| 商洛市| 新野县| 安康市| 都江堰市| 黄骅市| 普陀区| 简阳市| 澜沧| 沈阳市| 富川| 乡宁县| 昌江| 景洪市| 汾阳市| 巨野县| 香格里拉县| 上饶县| 镇宁| 昌邑市| 宽甸| 盐津县| 凤冈县| 抚顺县| 会昌县| 漳浦县| 舟曲县| 肥乡县| 巴彦淖尔市| 门头沟区| 四平市| 鞍山市| 永年县| 内江市| 儋州市| 定兴县|