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

Python 2.7.x 和 3.x 版本的重要區(qū)別小結

 更新時間:2014年11月28日 15:18:28   投稿:mdxy-dxy  
這篇文章主要介紹了Python 2.7.x 和 3.x 版本的重要區(qū)別小結,需要的朋友可以參考下

許多Python初學者都會問:我應該學習哪個版本的Python。對于這個問題,我的回答通常是“先選擇一個最適合你的Python教程,教程中使用哪個版本的Python,你就用那個版本。等學得差不多了,再來研究不同版本之間的差別”。

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

目錄

__future__模塊

[回到目錄]

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

from __future__ import division

下表列出了__future__中其他可導入的特性:

特性 可選版本 強制版本 效果
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

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

示例:

from platform import python_version

print函數

[回到目錄]

雖然print語法是Python 3中一個很小的改動,且應該已經廣為人知,但依然值得提一下:Python 2中的print語句被Python 3中的print()函數取代,這意味著在Python 3中必須用括號將需要輸出的對象括起來。

在Python 2中使用額外的括號也是可以的。但反過來在Python 3中想以Python2的形式不帶括號調用print函數時,會觸發(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中,帶不帶括號輸出”Hello World”都很正常。但如果在圓括號中同時輸出多個對象時,就會創(chuàng)建一個元組,這是因為在Python 2中,print是一個語句,而不是函數調用。

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

整數除法

[回到目錄]

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

所以,我還是會在Python 3的腳本中嘗試用float(3)/2或 3/2.0代替3/2,以此來避免代碼在Python 2環(huán)境下可能導致的錯誤(或與之相反,在Python 2腳本中用from __future__ import division來使用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 2.7.6
3 / 2 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.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)
Python 3.4.1
3 / 2 = 1.5
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0

Unicode

[回到目錄]

Python 2有基于ASCII的str()類型,其可通過單獨的unicode()函數轉成unicode類型,但沒有byte類型。

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

Python 2

print 'Python', python_version()
Python 2.7.6
print type(unicode('this is like a python3 str type'))
<type 'unicode'>
print type(b'byte type does not exist')
<type 'str'>
print 'they are really' + b' the same'
they are really the same
print type(bytearray(b'bytearray oddly does exist though'))
<type 'bytearray'>

Python 3

print('Python', python_version())
print('strings are now utf-8 u03BCnicou0394é!')
Python 3.4.1
strings are now utf-8 μnicoΔé!
print('Python', python_version(), end="")
print(' has', type(b' bytes for storing data'))
Python 3.4.1 has <class 'bytes'>
print('and Python', python_version(), end="")
print(' also has', type(bytearray(b'bytearrays')))
and Python 3.4.1 also has <class 'bytearray'>
'note that we cannot add a string' + b'bytes for data'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-d3e8942ccf81> in <module>()
----> 1 'note that we cannot add a string' + b'bytes for data'
 
TypeError: Can't convert 'bytes' object to str implicitly

xrange

[回到目錄]

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

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

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

在Python 3中,range()的實現方式與xrange()函數相同,所以就不存在專用的xrange()(在Python 3中使用xrange()會觸發(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 2.7.6
 
timing range()
1000 loops, best of 3: 433 µs per loop
 
timing xrange()
1000 loops, best of 3: 350 µs per loop

Python 3

print('Python', python_version())
 
print('ntiming range()')
%timeit test_range(n)
Python 3.4.1
 
timing range()
1000 loops, best of 3: 520 µs per loop
print(xrange(10))
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in ()
----> 1 print(xrange(10))
 
NameError: name 'xrange' is not defined

Python 3中的range對象中的__contains__方法

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

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)
Python 3.4.1
1 loops, best of 3: 742 ms per loop
1000000 loops, best of 3: 1.19 µs per loop

根據上面的timeit的結果,查找整數比查找浮點數要快大約6萬倍。但由于Python 2.x中的range或xrange沒有__contains__方法,所以在Python 2中的整數和浮點數的查找速度差別不大。

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.7.7
1 loops, best of 3: 285 ms per loop
1 loops, best of 3: 179 ms per loop
1 loops, best of 3: 658 ms per loop
1 loops, best of 3: 556 ms per loop

下面的代碼證明了Python 2.x中沒有__contain__方法:

print('Python', python_version())
range.__contains__
Python 3.4.1
<slot wrapper '__contains__' of 'range' objects
print('Python', python_version())
range.__contains__
Python 2.7.7
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-05327350dafb> in <module>()
1 print 'Python', python_version()
----> 2 range.__contains__
 
AttributeError: 'builtin_function_or_method' object has no attribute '__contains__'
print('Python', python_version())
xrange.__contains__
Python 2.7.7
 
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in ()
1 print 'Python', python_version()
----> 2 xrange.__contains__
 
AttributeError: type object 'xrange' has no attribute '__contains__'

關于Python 2中xrange()與Python 3中range()之間的速度差異的一點說明:

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

def test_while():
 i = 0
 while i < 20000:
  i += 1
 return
print('Python', python_version())
%timeit test_while()
Python 3.4.1
%timeit test_while()
100 loops, best of 3: 2.68 ms per loop
print 'Python', python_version()
%timeit test_while()
Python 2.7.6
1000 loops, best of 3: 1.72 ms per loop

觸發(fā)異常

[回到目錄]

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

Python 2

print 'Python', python_version()
Python 2.7.6
raise IOError, "file error"
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-8-25f049caebb0> in <module>()
----> 1 raise IOError, "file error"
 
IOError: file error
raise IOError("file error")
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-9-6f1c43f525b2> in <module>()
----> 1 raise IOError("file error")
 
IOError: file error

Python 3

print('Python', python_version())
Python 3.4.1
raise IOError, "file error"
File "<ipython-input-10-25f049caebb0>", line 1
raise IOError, "file error"
^
SyntaxError: invalid syntax
The proper way to raise an exception in Python 3:
print('Python', python_version())
raise IOError("file error")
Python 3.4.1
 
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-11-c350544d15da> in <module>()
1 print('Python', python_version())
----> 2 raise IOError("file error")
 
OSError: file error

異常處理

[回到目錄]

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

Python 2

print 'Python', python_version()
try:
 let_us_cause_a_NameError
except NameError, err:
 print err, '--> our error message'
Python 2.7.6
name 'let_us_cause_a_NameError' is not defined --> our error message

Python 3

print('Python', python_version())
try:
 let_us_cause_a_NameError
except NameError as err:
 print(err, '--> our error message')
Python 3.4.1
name 'let_us_cause_a_NameError' is not defined --> our error message

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

[回到目錄]

由于會經常用到next()(.next())函數(方法),所以還要提到另一個語法改動(實現方面也做了改動):在Python 2.7.5中,函數形式和方法形式都可以使用,而在Python 3中,只能使用next()函數(試圖調用.next()方法會觸發(fā)AttributeError)。

Python 2

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

Python 3

print('Python', python_version())
my_generator = (letter for letter in 'abcdefg')
next(my_generator)
Python 3.4.1
'a'
my_generator.next()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-14-125f388bb61b> in <module>()
----> 1 my_generator.next()
 
AttributeError: 'generator' object has no attribute 'next'

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

[回到目錄]

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

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

“列表推導不再支持[... for var in item1, item2, ...]這樣的語法,使用[... for var in (item1, item2, ...)]代替。還要注意列表推導有不同的語義:現在列表推導更接近list()構造器中的生成器表達式這樣的語法糖,特別要注意的是,循環(huán)控制變量不會再泄漏到循環(huán)周圍的空間中了。”

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 2.7.6
before: i = 1
comprehension: [0, 1, 2, 3, 4]
after: i = 4

Python 3

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

比較無序類型

[回到目錄]

Python 3中另一個優(yōu)秀的改動是,如果我們試圖比較無序類型,會觸發(fā)一個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 2.7.6
[1, 2] > 'foo' = False
(1, 2) > 'foo' = True
[1, 2] > (1, 2) = False

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))
Python 3.4.1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-a9031729f4a0> in <module>()
1 print('Python', python_version())
----> 2 print("[1, 2] > 'foo' = ", [1, 2] > 'foo')
3 print("(1, 2) > 'foo' = ", (1, 2) > 'foo')
4 print("[1, 2] > (1, 2) = ", [1, 2] > (1, 2))
TypeError: unorderable types: list() > str()

通過input()解析用戶的輸入

[回到目錄]

幸運的是,Python 3改進了input()函數,這樣該函數就會總是將用戶的輸入存儲為str對象。在Python 2中,為了避免讀取非字符串類型會發(fā)生的一些危險行為,不得不使用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'>

返回可迭代對象,而不是列表

[回到目錄]

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

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

此時我們的確需要列表對象,可以通過list()函數簡單的將可迭代對象轉成列表。

Python 2

print 'Python', python_version()
 
print range(3)
print type(range(3))
Python 2.7.6
[0, 1, 2]
<type 'list'>

Python 3

print('Python', python_version())
print(range(3))
print(type(range(3)))
print(list(range(3)))
Python 3.4.1
range(0, 3)
<class 'range'>
[0, 1, 2]

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

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

更多關于Python 2和Python 3的文章

[回到目錄]

下面列出了其他一些可以進一步了解Python 2和Python 3的優(yōu)秀文章,

//遷移到 Python 3

// 對Python 3的褒與貶

相關文章

  • 火遍全網的Python二次元特效輕松掌握

    火遍全網的Python二次元特效輕松掌握

    本篇文章介紹了用python編寫的二次元特效變化小程序,詳細介紹了整個思路和過程以及代碼,通讀本篇對大家的學習或工作具有一定的價值,需要的朋友可以參考下
    2021-09-09
  • 在Python中調用ggplot的三種方法

    在Python中調用ggplot的三種方法

    這篇文章主要介紹了在Python中調用ggplot的三種方法,ggplot作為一個圖形庫,經常被用來制作數據的可視化視圖,需要的朋友可以參考下
    2015-04-04
  • 雙向RNN:bidirectional_dynamic_rnn()函數的使用詳解

    雙向RNN:bidirectional_dynamic_rnn()函數的使用詳解

    今天小編就為大家分享一篇雙向RNN:bidirectional_dynamic_rnn()函數的使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • python上下文管理器異常問題解決方法

    python上下文管理器異常問題解決方法

    在本篇文章里小編給大家整理的是一篇關于python上下文管理器異常問題解決方法,對此有興趣的朋友們可以學習參考下。
    2021-02-02
  • python識別圖標并點擊功能實現

    python識別圖標并點擊功能實現

    這篇文章主要介紹了python識別圖標并點擊功能實現,本文給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
    2024-07-07
  • Python?Flask-Login構建強大的用戶認證系統(tǒng)實例探究

    Python?Flask-Login構建強大的用戶認證系統(tǒng)實例探究

    這篇文章主要為大家介紹了Python?Flask-Login構建強大的用戶認證系統(tǒng)示例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2024-01-01
  • Python實現GUI學生信息管理系統(tǒng)

    Python實現GUI學生信息管理系統(tǒng)

    這篇文章主要為大家詳細介紹了Python實現GUI學生信息管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Python列表append()函數使用方法詳解

    Python列表append()函數使用方法詳解

    python中的append()函數是在列表末尾添加新的對象,且將添加的對象最為一個整體,下面這篇文章主要給大家介紹了關于Python列表append()函數使用方法的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-06-06
  • Python3+Appium實現多臺移動設備操作的方法

    Python3+Appium實現多臺移動設備操作的方法

    這篇文章主要介紹了Python3+Appium實現多臺移動設備操作的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-07-07
  • 只需要100行Python代碼就可以實現的貪吃蛇小游戲

    只需要100行Python代碼就可以實現的貪吃蛇小游戲

    貪吃蛇小游戲相信80、90后小時候肯定都玩過,那么你知道如果通過Python來實現嗎?今天就來教大家,文中有非常詳細的代碼示例,對正在學習python的小伙伴們很有幫助,需要的朋友可以參考下
    2021-05-05

最新評論

区。| 达尔| 五大连池市| 博罗县| 贵州省| 永川市| 龙口市| 衢州市| 承德县| 新民市| 长宁县| 邯郸县| 儋州市| 珠海市| 林芝县| 获嘉县| 柳江县| 东莞市| 朝阳区| 沂源县| 来宾市| 西盟| 澳门| 措勤县| 彭山县| 邯郸县| 五大连池市| 泌阳县| 和硕县| 城步| 衡南县| 呼伦贝尔市| 攀枝花市| 札达县| 偃师市| 遂溪县| 讷河市| 宜兰县| 公安县| 日照市| 宜章县|