python3和Python2的區別

1、print函數

python2 的 print 聲明已經被 print() 函數取代了,這意味着咱們必須包裝咱們想打印在小括號中的對象

2、經過input()解析用戶的輸入

  • python3中input獲得的爲str,python3中沒有raw_input
  • Python2的input的到的爲int型,Python2的raw_input獲得的爲str類型

3、整除

  • Python3中/表示真除,%表示取餘,//表示地板除(結果取整)
  • Python2中/表示根據除數被除數小數點位獲得結果,//一樣表示地板除)

python2python

1     from platform import python_version 2     print 'Python', python_version() 3     print '5 / 3 =', 5 / 3
4     print '3 // 2 =', 3 // 2
5     print '3 / 2.0 =', 3 / 2.0
6     print '3 // 2.0 =', 3 // 2.0

Python 2.7.10
5 / 3 = 1
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0編程

python3數組

1     from platform import python_version 2     print('Python', python_version()) 3     print('5 / 3 =', 5 / 3) 4     print('3 // 2 =', 3 // 2) 5     print('3 / 2.0 =', 3 / 2.0) 6     print('3 // 2.0 =', 3 // 2.0)

Python 3.6.0
5 / 3 = 1.6666666666666667
3 // 2 = 1
3 / 2.0 = 1.5
3 // 2.0 = 1.0less

4、xrange模塊

python2 : range( 0, 4 ) 結果 是 列表 [0,1,2,3 ]
python3改成:list( range(0,4) )
python2原 : xrange( 0, 4 ) 適用於 for 循環的變量控制

python3改成:range(0,4)

 

  • python3
    在 Python 3 中,range() 是像 xrange() 那樣實現以致於一個專門的 xrange() 函數都再也不存在(在 Python 3 中xrange() 會拋出命名異常)。
  • python2
    在 Python 2 中 xrange() 建立迭代對象的用法是很是流行的。好比: for 循環或者是列表/集合/字典推導式ide

    這個表現十分像生成器(好比。「惰性求值」)。可是這個 xrange-iterable 是無窮的,意味着你能夠無限遍歷。因爲它的惰性求值,若是你不只僅遍歷它一次,xrange() 函數 比 range() 更快(好比 for 循環)。儘管如此,對比迭代一次,不建議你重複迭代屢次,由於生成器每次都從頭開始。函數式編程

5、字符串

原: 字符串以 8-bit 字符串存儲
改成: 字符串以 16-bit Unicode 字符串存儲

 

6、try except 語句的變化

在 Python 3 中處理異常也輕微的改變了,在 Python 3 中咱們如今使用 as 做爲關鍵詞。
捕獲異常的語法由 except exc, var 改成 except exc as var。

使用語法except (exc1, exc2) as var能夠同時捕獲多種類別的異常。 Python 2.6已經支持這兩種語法。
    1. 在2.x時代,全部類型的對象都是能夠被直接拋出的,在3.x時代,只有繼承自BaseException的對象才能夠被拋出。
    2. 2.x raise語句使用逗號將拋出對象類型和參數分開,3.x取消了這種奇葩的寫法,直接調用構造函數拋出對象便可。
在2.x時代,異常在代碼中除了表示程序錯誤,還常常作一些普通控制結構應該作的事情,在3.x中能夠看出,設計者讓異常變的更加專注,只有在錯誤發生的狀況才能去用異常捕獲語句來處理。

 

1     原: try: 2      ...... 3       except Exception, e : 4      ...... 5  改成 6       try: 7      ...... 8       except Exception as e : 9         ......

 

7、打開文件

原: file( ..... )
    或 open(.....)
    改成:
    只能用 open(.....)

 

8、bytes 數據類型 -- 新增

1)Py3.X去除了long類型,如今只有一種整型——int,但它的行爲就像2.X版本的long
2)新增了bytes類型,對應於2.X版本的八位串,定義一個bytes字面量的方法以下:
1     >>> b = b'china'
2     >>> type(b) 3     <type 'bytes'>
str對象和bytes對象可使用.encode() (str -> bytes) or .decode() (bytes -> str)方法相互轉化
1     >>>s = b.decode() 2     >>> s 3     'china'
4     >>> b1 = s.encode() 5     >>> b1 6     b'china'
A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 <= x < 256.
bytes 能夠當作是「字節數組」對象,每一個元素是 8-bit 的字節,取值範圍 0~255。
因爲在 python 3.0中字符串以 unicode 編碼存儲,當寫入二進制文件時,字符串沒法直接寫入(或讀取),必須以某種方式的編碼爲字節序列後,方可寫入。

(一)字符串編碼(encode) 爲 bytes函數

例: s = "張三abc12"
    b = s.encode( 編碼方式)
    # b 就是 bytes 類型的數據
    # 經常使用的編碼方式爲 : "uft-16" , "utf-8", "gbk", "gb2312", "ascii" , "latin1" 等
    # 注 : 當字符串不能編碼爲指定的「編碼方式」時,會引起異常

 

(二) bytes 解碼(decode)爲字符串ui

1      s = "張三abc12"
2     b = s.encode( "gbk") # 字符串 s 編碼爲 gbk 格式的字節序列
3     s1 = b.decode("gbk") # 將字節序列 b以gbk格式 解碼爲字符串
4     # 說明,當字節序列不能以指定的編碼格式解碼時會引起異常

 

(三)使用方法舉例編碼

 1     #coding=gbk
 2     f = open("c:\\1234.txt", "wb")  3     s = "張三李四abcd1234"
 4     # -------------------------------
 5     # 在 python2.4 中咱們能夠這樣寫:
 6     # f.write( s )
 7     # 但在 python 3.0中會引起異常
 8     # -------------------------------
 9     b = s.encode("gbk") 10  f.write( b ) 11  f.close() 12     input("?")

 

讀取該文件的例子:spa

 1     #coding=gbk
 2     f = open("c:\\1234.txt", "rb")  3     f.seek(0,2) #定位至文件尾
 4     n = f.tell() #讀取文件的字節數
 5     f.seek(0,0) #從新定位至文件開始處
 6     b = f.read( n )  7     # ------------------------------
 8     # 在 python 2.4 中 b 是字符串類型
 9     # 而 python 3.0 中 b 是 bytes 類型
10     # 所以須要按指定的編碼方式確碼
11     # ------------------------------
12     s = b.decode("gbk") 13     print ( s ) 14     # ------------------------------
15     # 在 python 2.4 中 能夠寫做 print s 或 print ( s )
16     # 要 python 3.0 中 必須寫做 print ( s )
17     # ------------------------------
18  f.close() 19     input("?")

 

運行後應顯示:
張三李四abcd1234

(四) python3中bytes序列,一但造成,其內容是不可變的
例:

1     s="ABCD"
2     b=s.encode("gbk") 3     print b[0] # 顯示 65
4     b[0] = 66
5     # 執行該句,出現異常: 'bytes' object does not support item assignment

9、chr( K ) 與 ord( c )

ord()函數主要用來返回對應字符的ascii碼,chr()主要用來表示ascii碼對應的字符他的輸入時數字,能夠用十進制,也能夠用十六進制
python 2.4.2之前
    chr( K ) 將編碼K 轉爲字符,K的範圍是 0 ~ 255
    ord( c ) 取單個字符的編碼, 返回值的範圍: 0 ~ 255
python 3.0
    chr( K ) 將編碼K 轉爲字符,K的範圍是 0 ~ 65535
    ord( c ) 取單個字符的編碼, 返回值的範圍: 0 ~ 65535

 

10、字節數組對象bytearray -- 新增

(一) 初始化

a = bytearray( 10 )
    # a 是一個由十個字節組成的數組,其每一個元素是一個字節,類型借用 int
    # 此時,每一個元素初始值爲 0

 

(二) 字節數組 是可變的

a = bytearray( 10 )
    a[0] = 25
    # 能夠用賦值語句更改其元素,但所賦的值必須在 0 ~ 255 之間

(三) 字節數組的切片還是字節數組
(四) 字符串轉化爲字節數組

1     #coding=gbk
2     s ="你好"
3     b = s.encode( "gbk") # 先將字符串按某種「GBK」編碼方式轉化爲 bytes
4     c = bytearray( b ) #再將 bytes 轉化爲 字節數組
5     # 也能夠寫做
6     c = bytearray( "你好", "gbk")
View Code

(五) 字節數組轉化爲字符串

1      c = bytearray( 4 ) 2     c[0] = 65 ; c[1]=66; c[2]= 67; c[3]= 68
3     s = c.decode( "gbk" ) 4     print ( s ) 5     # 應顯示: ABCD

(六) 字節數組可用於寫入文本文件

 1     #coding=gbk
 2     f = open("c:\\1234.txt", "wb")  3     s = "張三李四abcd1234"
 4     # -------------------------------
 5     # 在 python2.4 中咱們能夠這樣寫:
 6     # f.write( s )
 7     # 但在 python 3.0中會引起異常
 8     # -------------------------------
 9     b = s.encode("gbk") 10  f.write( b ) 11     # 或者
12     c=bytearray( s,"gbk") 13  f.write( c ) 14  f.close() 15     input("?")

 

11、「import thread」問題

2.x中的模塊thread在3.x中編程"_thread"(須要在前面加一個下劃線).不然會出現「ImportError: No module named thread

 

12、不等運算符

Python 2.x中不等於有兩種寫法 != 和 <> Python 3.x中去掉了<>, 只有!=一種寫法,還好,我歷來沒有使用<>的習慣

 

十3、去掉了repr表達式``

Python 2.x 中反引號``至關於repr函數的做用 Python 3.x 中去掉了``這種寫法,只容許使用repr函數,這樣作的目的是爲了使代碼看上去更清晰麼?不過我感受用repr的機會不多,通常只在debug的時候才用,多數時候仍是用str函數來用字符串描述對象。

 

十4、dict

dict的.keys()、.items 和.values()方法返回迭代器,而以前的iterkeys()等函數都被廢棄。同時去掉的還有 dict.has_key(),用 in替代它吧 。

 

十5、map、filter 和 reduce

這三個函數號稱是函數式編程的表明。在 Python3.x 和 Python2.x 中也有了很大的差別。 首先咱們先簡單的在 Python2.x 的交互下輸入 map 和 filter,看到它們二者的類型是 built-in function(內置函數):

 

python2.x它們輸出的結果類型都是列表
1     >>> map(lambda x:x *2, [1,2,3]) 2     [2, 4, 6] 3     >>> filter(lambda x:x %2 ==0,range(10)) 4     [0, 2, 4, 6, 8] 5     >>>
可是在Python 3.x中它們卻不是這個樣子了:
1     >>> map 2     <class 'map'>
3     >>> map(print,[1,2,3]) 4     <map object at 0x10d8bd400>
5     >>> filter 6     <class 'filter'>
7     >>> filter(lambda x:x % 2 == 0, range(10)) 8     <filter object at 0x10d8bd3c8>
9     >>>

 

首先它們從函數變成了類,其次,它們的返回結果也從當初的列表成了一個可迭代的對象, 咱們嘗試用 next 函數來進行手工迭代:
 1     >>> f =filter(lambda x:x %2 ==0, range(10))  2     >>> next(f)  3  0  4     >>> next(f)  5     2
 6     >>> next(f)  7     4
 8     >>> next(f)  9     6
10     >>>

 

對於比較高端的 reduce 函數,它在 Python 3.x 中已經不屬於 built-in 了,被挪到 functools 模塊當中
1     >>> import functools 2     >>> b = functools.reduce(lambda x, y: x + y, [1, 3, 4, 5]) 3     >>> print(b) 4     13
5     >>>

 

十6、cmp()函數的新函數(gt,ge,eq,le,lt)

Python3中已經不能使用cmp()函數了,被以下五個函數替代:
1     import operator #首先要導入運算符模塊
2     operator.gt(1,2) #意思是greater than(大於)
3     operator.ge(1,2) #意思是greater and equal(大於等於)
4     operator.eq(1,2) #意思是equal(等於)
5     operator.le(1,2) #意思是less and equal(小於等於)
6     operator.lt(1,2) #意思是less than(小於)

 

十7、sort,sorted

Sort函數是list列表中的函數,而sorted能夠對list或者iterator進行排序。
Python3.x和Python2.x的sorted函數有點不太同樣,少了cmp參數。下面本渣渣主要基於Python2.x的sorted函數進行講解,Python3.x直接忽略cmp這個參數便可,爲了保證代碼通用性,不建議你們在從此的編程中使用cmp參數

下面咱們使用help來查看他們的用法及功能:

 

python2:

1     >>> help(list.sort) 2  Help on method_descriptor: 3  sort(...) 4     L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; 5     cmp(x, y) -> -1, 0, 1
6     >>> help(sorted) 7     Help on built-in function sorted in module __builtin__: 8  sorted(...) 9     sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

 

python3:

 1 >>> help(list.sort)  2 Help on method_descriptor:  3 sort(...)  4   L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
 5 >>> help(sorted)  6 Help on built-in function sorted in module builtins:  7 sorted(iterable, key=None, reverse=False)  8   Return a new list containing all items from the iterable in ascending order.  9   A custom key function can be supplied to customize the sort order, and the 10   reverse flag can be set to request the result in descending order.

 

用sort函數對列表排序時會影響列表自己,而sorted不會。二者用法差很少。

以sorted爲例,sorted(iterable,cmp,key,reverse)

參數: 
- iterable能夠是list或者iterator; 
- cmp是帶兩個參數的比較函數; 
- key 是帶一個參數的函數; 
- reverse爲False或者True;

 

舉例說明:
(1)用cmp函數排序:

1     >>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)] 2     >>> sorted(list1,cmp = lambda x,y: cmp(x[0],y[0])) 3     [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)] 4     >>> sorted(list1,cmp = lambda x,y: cmp(x[1],y[1])) 5     [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]

 

(2)用key函數排序:

1     >>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)] 2     >>> sorted(list1,key = lambda list1: list1[0]) 3     [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)] 4     >>> sorted(list1,key = lambda list1: list1[1]) 5     [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]

 

(3)用reverse排序:

1  >>> sorted(list1,reverse = True) 2     [('sara', 80), ('mary', 90), ('lily', 95), ('david', 90)]

 

(4)用operator.itemgetter函數排序:

1     >>> from operator import itemgetter 2     >>> sorted(list1, key=itemgetter(1)) 3     [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)] 4     >>> sorted(list1, key=itemgetter(0)) 5     [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]

 

介紹operator.itemgetter函數:
operator.itemgetter函數獲取的不是值,而是定義了一個函數。該函數是C語言實現,比python速度快。

1     >>> import operator 2     >>> a = [1,2,3] 3     >>> b = operator.itemgetter(0) 4     >>> b(a) 5     1

 

(5)多級排序:

1         >>> sorted(list1, key=itemgetter(0,1)) 2         [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
相關文章
相關標籤/搜索