亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python2與Python3的區(qū)別詳解

 更新時(shí)間:2020年02月09日 13:39:36   作者:羅阿紅  
這篇文章主要介紹了Python2與Python3的區(qū)別詳解,需要的朋友可以參考下

許多Python初學(xué)者都會(huì)問(wèn):我應(yīng)該學(xué)習(xí)哪個(gè)版本的Python。對(duì)于這個(gè)問(wèn)題,我的回答通常是“先選擇一個(gè)最適合你的Python教程,教程中使用哪個(gè)版本的Python,你就用那個(gè)版本。等學(xué)得差不多了,再來(lái)研究不同版本之間的差別”。

但如果想要用Python開(kāi)發(fā)一個(gè)新項(xiàng)目,那么該如何選擇Python版本呢?我可以負(fù)責(zé)任的說(shuō),大部分Python庫(kù)都同時(shí)支持Python 2.7.x和3.x版本的,所以不論選擇哪個(gè)版本都是可以的。但為了在使用Python時(shí)避開(kāi)某些版本中一些常見(jiàn)的陷阱,或需要移植某個(gè)Python項(xiàng)目時(shí),依然有必要了解一下Python兩個(gè)常見(jiàn)版本之間的主要區(qū)別。

本節(jié)內(nèi)容

  • 使用__future__模塊
  • print函數(shù)
  • 整數(shù)除法
  • Unicode
  • xrange
  • 觸發(fā)異常
  • 處理異常
  • next()函數(shù)和.next()方法
  • For循環(huán)變量與全局命名空間泄漏
  • 比較無(wú)序類型
  • 使用input()解析輸入內(nèi)容
  • 返回可迭代對(duì)象,而不是列表

一、__future__模塊

Python 3.x引入了一些與Python 2不兼容的關(guān)鍵字和特性,在Python 2中,可以通過(guò)內(nèi)置的__future__模塊導(dǎo)入這些新內(nèi)容。如果你希望在Python 2環(huán)境下寫的代碼也可以在Python 3.x中運(yùn)行,那么建議使用__future__模塊。例如,如果希望在Python 2中擁有Python 3.x的整數(shù)除法行為,可以通過(guò)下面的語(yǔ)句導(dǎo)入相應(yīng)的模塊。

from __future__ import division

下表列出了__future__中其他可導(dǎo)入的特性:

特性 可選版本 強(qiáng)制版本 效果
nested_scopes 2.1.0b1 2.2 PEP 227:
Statically Nested Scopes
generators 2.2.0a1 2.3 PEP 255:
Simple Generators
division 2.2.0a2 3.0 PEP 238:
Changing the Division Operator
absolute_import 2.5.0a1 3.0 PEP 328:
Imports: Multi-Line and Absolute/Relative
with_statement 2.5.0a1 2.6 PEP 343:
The “with” Statement
print_function 2.6.0a2 3.0 PEP 3105:
Make print a function
unicode_literals 2.6.0a2 3.0 PEP 3112:
Bytes literals in Python 3000

(來(lái)源: https://docs.python.org/2/library/future.html)

示例:

from platform import python_version

二、print函數(shù)

雖然print語(yǔ)法是Python 3中一個(gè)很小的改動(dòng),且應(yīng)該已經(jīng)廣為人知,但依然值得提一下:Python 2中的print語(yǔ)句被Python 3中的print()函數(shù)取代,這意味著在Python 3中必須用括號(hào)將需要輸出的對(duì)象括起來(lái)。

在Python 2中使用額外的括號(hào)也是可以的。但反過(guò)來(lái)在Python 3中想以Python2的形式不帶括號(hào)調(diào)用print函數(shù)時(shí),會(huì)觸發(fā)SyntaxError。

Python 2

print 'Python', python_version()
print 'Hello, World!'
print('Hello, World!')
print "text", ; print 'print more text on the same line'
Python 2.7.6
Hello, World!
Hello, World!
text print more text on the same line

Python 3

print('Python', python_version())
print('Hello, World!')

print("some text,", end="") 
print(' print more text on the same line')
Python 3.4.1
Hello, World!
some text, print more text on the same line
print 'Hello, World!'
File "<ipython-input-3-139a7c5835bd>", line 1
print 'Hello, World!'
^
SyntaxError: invalid syntax

注意:

在Python中,帶不帶括號(hào)輸出”Hello World”都很正常。但如果在圓括號(hào)中同時(shí)輸出多個(gè)對(duì)象時(shí),就會(huì)創(chuàng)建一個(gè)元組,這是因?yàn)樵赑ython 2中,print是一個(gè)語(yǔ)句,而不是函數(shù)調(diào)用。

print 'Python', python_version()
print('a', 'b')
print 'a', 'b'

三、整數(shù)除法

由于人們常常會(huì)忽視Python 3在整數(shù)除法上的改動(dòng)(寫錯(cuò)了也不會(huì)觸發(fā)Syntax Error),所以在移植代碼或在Python 2中執(zhí)行Python 3的代碼時(shí),需要特別注意這個(gè)改動(dòng)。

所以,我還是會(huì)在Python 3的腳本中嘗試用float(3)/2或 3/2.0代替3/2,以此來(lái)避免代碼在Python 2環(huán)境下可能導(dǎo)致的錯(cuò)誤(或與之相反,在Python 2腳本中用from __future__ import division來(lái)使用Python 3的除法)。

Python 2

print 'Python', python_version()
print '3 / 2 =', 3 / 2
print '3 // 2 =', 3 // 2
print '3 / 2.0 =', 3 / 2.0
print '3 // 2.0 =', 3 // 2.0

Python 3

print('Python', python_version())
print('3 / 2 =', 3 / 2)
print('3 // 2 =', 3 // 2)
print('3 / 2.0 =', 3 / 2.0)
print('3 // 2.0 =', 3 // 2.0)

四、Unicode

Python 2有基于ASCII的str()類型,其可通過(guò)單獨(dú)的unicode()函數(shù)轉(zhuǎn)成unicode類型,但沒(méi)有byte類型。

而在Python 3中,終于有了Unicode(utf-8)字符串,以及兩個(gè)字節(jié)類:bytes和bytearrays。

Python 2

print 'Python', python_version()

print type(unicode('this is like a python3 str type'

print type(b'byte type does not exist')

print 'they are really' + b' the same'

print type(bytearray(b'bytearray oddly does exist though'))

Python 3

print('Python', python_version())

print('strings are now utf-8 u03BCnicou0394é!') 

print('Python', python_version(), end="")

print(' has', type(b' bytes for storing data'))
 

print('and Python', python_version(), end="")

print(' also has', type(bytearray(b'bytearrays'))
 

'note that we cannot add a string' + b'bytes for data'

五、xrange

在Python 2.x中,經(jīng)常會(huì)用xrange()創(chuàng)建一個(gè)可迭代對(duì)象,通常出現(xiàn)在“for循環(huán)”或“列表/集合/字典推導(dǎo)式”中。

這種行為與生成器非常相似(如”惰性求值“),但這里的xrange-iterable無(wú)盡的,意味著可能在這個(gè)xrange上無(wú)限迭代。

由于xrange的“惰性求知“特性,如果只需迭代一次(如for循環(huán)中),range()通常比xrange()快一些。不過(guò)不建議在多次迭代中使用range(),因?yàn)閞ange()每次都會(huì)在內(nèi)存中重新生成一個(gè)列表。

在Python 3中,range()的實(shí)現(xiàn)方式與xrange()函數(shù)相同,所以就不存在專用的xrange()(在Python 3中使用xrange()會(huì)觸發(fā)NameError)。

import timeit
 
n = 10000
def test_range(n):
 return for i in range(n):
 pass
 
def test_xrange(n):
 for i in xrange(n):
 pass

Python 2

print 'Python', python_version()
 
print 'ntiming range()'
%timeit test_range(n)
 
print 'nntiming xrange()'
%timeit test_xrange(n)

Python 3

print('Python', python_version())
 
print('ntiming range()')
%timeit test_range(n)
 
print(xrange(10))

六、Python 3中的range對(duì)象中的__contains__方法

另一個(gè)值得一提的是,在Python 3.x中,range有了一個(gè)新的__contains__方法。__contains__方法可以有效的加快Python 3.x中整數(shù)和布爾型的“查找”速度。

x = 10000000
def val_in_range(x, val):
 return val in range(x)
 
def val_in_xrange(x, val):
 return val in xrange(x)
 
print('Python', python_version())
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_range(x, x/2)
%timeit val_in_range(x, x//2)

根據(jù)上面的timeit的結(jié)果,查找整數(shù)比查找浮點(diǎn)數(shù)要快大約6萬(wàn)倍。但由于Python 2.x中的range或xrange沒(méi)有__contains__方法,所以在Python 2中的整數(shù)和浮點(diǎn)數(shù)的查找速度差別不大。

print 'Python', python_version()
 
assert(val_in_xrange(x, x/2.0) == True)
assert(val_in_xrange(x, x/2) == True)
assert(val_in_range(x, x/2) == True)
assert(val_in_range(x, x//2) == True)
%timeit val_in_xrange(x, x/2.0)
%timeit val_in_xrange(x, x/2)
%timeit val_in_range(x, x/2.0)
%timeit val_in_range(x, x/2)

下面的代碼證明了Python 2.x中沒(méi)有__contain__方法:

print('Python', python_version())
range.__contains__
 
print('Python', python_version())
range.__contains__
 
print('Python', python_version())
xrange.__contains__

關(guān)于Python 2中xrange()與Python 3中range()之間的速度差異的一點(diǎn)說(shuō)明:

有讀者指出了Python 3中的range()和Python 2中xrange()執(zhí)行速度有差異。由于這兩者的實(shí)現(xiàn)方式相同,因此理論上執(zhí)行速度應(yīng)該也是相同的。這里的速度差別僅僅是因?yàn)镻ython 3的總體速度就比Python 2慢。

def test_while():
 i = 0
 while i < 20000:
 i += 1
 return
 
print('Python', python_version())
%timeit test_while()
 
print 'Python', python_version()
%timeit test_while()

   

七、觸發(fā)異常

Python 2支持新舊兩種異常觸發(fā)語(yǔ)法,而Python 3只接受帶括號(hào)的的語(yǔ)法(不然會(huì)觸發(fā)SyntaxError):

Python 2

print 'Python', python_version(
 
raise IOError, "file error"
 
raise IOError("file error")

Python 3

print('Python', python_version())
 
raise IOError, "file error"
 
print('Python', python_version())
raise IOError("file error")

八、異常處理

Python 3中的異常處理也發(fā)生了一點(diǎn)變化。在Python 3中必須使用“as”關(guān)鍵字。

Python 2

print 'Python', python_version()
try:
 let_us_cause_a_NameError
except NameError, err:
 print err, '--> our error message'

Python 3

print('Python', python_version())
try:
 let_us_cause_a_NameError
except NameError as err:
 print(err, '--> our error message')

next()函數(shù)和.next()方法

由于會(huì)經(jīng)常用到next()(.next())函數(shù)(方法),所以還要提到另一個(gè)語(yǔ)法改動(dòng)(實(shí)現(xiàn)方面也做了改動(dòng)):在Python 2.7.5中,函數(shù)形式和方法形式都可以使用,而在Python 3中,只能使用next()函數(shù)(試圖調(diào)用.next()方法會(huì)觸發(fā)AttributeError)。

Python 2

print 'Python', python_version()
my_generator = (letter for letter in 'abcdefg')
next(my_generator)
my_generator.next()

Python 3

print('Python', python_version())
my_generator = (letter for letter in 'abcdefg')
next(my_generator)
 
my_generator.next()

九、For循環(huán)變量與全局命名空間泄漏

好消息是:在Python 3.x中,for循環(huán)中的變量不再會(huì)泄漏到全局命名空間中了!

這是Python 3.x中做的一個(gè)改動(dòng),在“What's New In Python 3.0”中有如下描述:

“列表推導(dǎo)不再支持[… for var in item1, item2, …]這樣的語(yǔ)法,使用[… for var in (item1, item2, …)]代替。還要注意列表推導(dǎo)有不同的語(yǔ)義:現(xiàn)在列表推導(dǎo)更接近list()構(gòu)造器中的生成器表達(dá)式這樣的語(yǔ)法糖,特別要注意的是,循環(huán)控制變量不會(huì)再泄漏到循環(huán)周圍的空間中了?!?/p>

Python 2

print 'Python', python_version()
 
i = 1
print 'before: i =', i
 
print 'comprehension: ', [i for i in range(5)]
 
print 'after: i =', i

Python 3

print('Python', python_version())
 
i = 1
print('before: i =', i)
 
print('comprehension:', [i for i in range(5)])
 
print('after: i =', i)

十、比較無(wú)序類型

Python 3中另一個(gè)優(yōu)秀的改動(dòng)是,如果我們?cè)噲D比較無(wú)序類型,會(huì)觸發(fā)一個(gè)TypeError。

Python 2

print 'Python', python_version()
print "[1, 2] > 'foo' = ", [1, 2] > 'foo'
print "(1, 2) > 'foo' = ", (1, 2) > 'foo'
print "[1, 2] > (1, 2) = ", [1, 2] > (1, 2)

Python 3

print('Python', python_version())
print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))

十一、通過(guò)input()解析用戶的輸入

幸運(yùn)的是,Python 3改進(jìn)了input()函數(shù),這樣該函數(shù)就會(huì)總是將用戶的輸入存儲(chǔ)為str對(duì)象。在Python 2中,為了避免讀取非字符串類型會(huì)發(fā)生的一些危險(xiǎn)行為,不得不使用raw_input()代替input()。

Python 2

Python 2.7.6
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 
>>> my_input = input('enter a number: ')
 
enter a number: 123
 
>>> type(my_input)
<type 'int'>
 
>>> my_input = raw_input('enter a number: ')
 
enter a number: 123
 
>>> type(my_input)
<type 'str'>

Python 3

Python 3.4.1
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 
>>> my_input = input('enter a number: ')
enter a number: 123
>>> type(my_input)
<class 'str'>

十二、返回可迭代對(duì)象,而不是列表

在xrange一節(jié)中可以看到,某些函數(shù)和方法在Python中返回的是可迭代對(duì)象,而不像在Python 2中返回列表。

由于通常對(duì)這些對(duì)象只遍歷一次,所以這種方式會(huì)節(jié)省很多內(nèi)存。然而,如果通過(guò)生成器來(lái)多次迭代這些對(duì)象,效率就不高了。

此時(shí)我們的確需要列表對(duì)象,可以通過(guò)list()函數(shù)簡(jiǎn)單的將可迭代對(duì)象轉(zhuǎn)成列表。

Python 2

print 'Python', python_version()
 
print range(3)
print type(range(3))

Python 3

print('Python', python_version())
print(range(3))
print(type(range(3)))
print(list(range(3)))

下面列出了Python 3中其他不再返回列表的常用函數(shù)和方法:

  • zip()
  • map()
  • filter()
  • 字典的.key()方法
  • 字典的.value()方法

更多關(guān)于python2和3區(qū)別請(qǐng)查看下面的相關(guān)鏈接

相關(guān)文章

  • Python壓縮模塊zipfile實(shí)現(xiàn)原理及用法解析

    Python壓縮模塊zipfile實(shí)現(xiàn)原理及用法解析

    這篇文章主要介紹了Python壓縮模塊zipfile實(shí)現(xiàn)原理及用法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • Python實(shí)現(xiàn)解析參數(shù)的三種方法詳解

    Python實(shí)現(xiàn)解析參數(shù)的三種方法詳解

    這篇文章主要介紹了python解析參數(shù)的三種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2022-07-07
  • python3 selenium自動(dòng)化測(cè)試 強(qiáng)大的CSS定位方法

    python3 selenium自動(dòng)化測(cè)試 強(qiáng)大的CSS定位方法

    今天小編就為大家分享一篇python3 selenium自動(dòng)化測(cè)試 強(qiáng)大的CSS定位方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-08-08
  • Python入門基礎(chǔ)之import機(jī)制

    Python入門基礎(chǔ)之import機(jī)制

    這篇文章主要給大家介紹了關(guān)于Python入門基礎(chǔ)之import機(jī)制的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • python 密碼學(xué)示例——?jiǎng)P撒密碼的實(shí)現(xiàn)

    python 密碼學(xué)示例——?jiǎng)P撒密碼的實(shí)現(xiàn)

    這篇文章主要介紹了python 密碼學(xué)示例——?jiǎng)P撒密碼的實(shí)現(xiàn),幫助大家更好的利用python處理密碼,感興趣的朋友可以了解下
    2020-09-09
  • 淺談python中頻繁的print到底能浪費(fèi)多長(zhǎng)時(shí)間

    淺談python中頻繁的print到底能浪費(fèi)多長(zhǎng)時(shí)間

    今天小編就為大家分享一篇淺談python中頻繁的print到底能浪費(fèi)多長(zhǎng)時(shí)間,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-02-02
  • Python中輸入若干整數(shù)以逗號(hào)間隔實(shí)現(xiàn)統(tǒng)計(jì)每個(gè)整數(shù)出現(xiàn)次數(shù)

    Python中輸入若干整數(shù)以逗號(hào)間隔實(shí)現(xiàn)統(tǒng)計(jì)每個(gè)整數(shù)出現(xiàn)次數(shù)

    這篇文章主要介紹了Python中輸入若干整數(shù)以逗號(hào)間隔實(shí)現(xiàn)統(tǒng)計(jì)每個(gè)整數(shù)出現(xiàn)次數(shù)的相關(guān)資料,需要的小伙伴可以參考一下,希望對(duì)你有所幫助
    2022-04-04
  • 8段用于數(shù)據(jù)清洗Python代碼(小結(jié))

    8段用于數(shù)據(jù)清洗Python代碼(小結(jié))

    這篇文章主要介紹了8段用于數(shù)據(jù)清洗Python代碼(小結(jié)),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-10-10
  • Python中的閉包總結(jié)

    Python中的閉包總結(jié)

    這篇文章主要介紹了Python中的閉包總結(jié),本文講解了閉包的概念、為什么使用閉包、使用閉包實(shí)例等內(nèi)容,需要的朋友可以參考下
    2014-09-09
  • Python數(shù)據(jù)可視化之畫圖

    Python數(shù)據(jù)可視化之畫圖

    今天小編就為大家分享一篇關(guān)于Python數(shù)據(jù)可視化之畫圖,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01

最新評(píng)論