Python高級特性之切片迭代列表生成式及生成器詳解
在Python中,代碼越少越好、越簡單越好。基于這一思想,需要掌握Python中非常有用的高級特性,1行代碼能實現(xiàn)的功能,決不寫5行代碼。代碼越少,開發(fā)效率越高。
切片
tuple,list,字符串都可以進行切片操作
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] L[0:3] # ['Michael', 'Sarah', 'Tracy'] L[:3] # ['Michael', 'Sarah', 'Tracy'] L[1:3] # ['Sarah', 'Tracy'] L[-2:] # ['Bob', 'Jack'] L[-2:-1] # ['Bob'] L = list(range(100)) L[:10] # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] L[-10:] # [90, 91, 92, 93, 94, 95, 96, 97, 98, 99] L[10:20] # [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] L[:10:2] # [0, 2, 4, 6, 8] L[::5] # [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] L[:] # [0, 1, 2, 3, ..., 99]
練習(xí)
利用切片操作,實現(xiàn)一個trim()函數(shù),去除字符串首尾的空格,注意不要調(diào)用str的strip()方法:
# -*- coding: utf-8 -*- def trim(s): for i in range(0,len(s)): if s[0] == ' ': s = s[1:] elif s[-1] == ' ': s = s[:-1] return s
迭代
任何可迭代對象都可以作用于for循環(huán),包括我們自定義的數(shù)據(jù)類型,只要符合迭代條件,就可以使用for循環(huán)
如何判斷一個對象是可迭代對象呢?方法是通過collections.abc模塊的Iterable類型判斷
Python內(nèi)置的enumerate函數(shù)可以把一個list變成索引-元素對,可以在for循環(huán)中同時迭代索引和元素本身
for i, value in enumerate(['A', 'B', 'C']): print(i, value)
練習(xí)
請使用迭代查找一個list中最小和最大值,并返回一個tuple:
# -*- coding: utf-8 -*- def findMinAndMax(L): max = min = None if(len(L)>0): L = list(L) max = min = L[0] for i in L: if i>max: max = i if i<min: min = i return (min,max)
列表生成式
列表生成式即List Comprehensions,是Python內(nèi)置的非常簡單卻強大的可以用來創(chuàng)建list的生成式
list(range(1, 11)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [x * x for x in range(1, 11)] # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] [x * x for x in range(1, 11) if x % 2 == 0] # [4, 16, 36, 64, 100] [m + n for m in 'ABC' for n in 'XYZ'] # ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ'] # 列表生成式也可以使用兩個變量來生成list d = {'x': 'A', 'y': 'B', 'z': 'C' } [k + '=' + v for k, v in d.items()] # ['y=B', 'x=A', 'z=C'] L = ['Hello', 'World', 'IBM', 'Apple'] [s.lower() for s in L] # ['hello', 'world', 'ibm', 'apple']
在一個列表生成式中,for前面的if … else是表達式,而for后面的if是過濾條件,不能帶else
[x for x in range(1, 11) if x % 2 == 0] # Right [x for x in range(1, 11) if x % 2 == 0 else 0] # WRONG! [x if x % 2 == 0 else -x for x in range(1, 11)] # Right [x if x % 2 == 0 for x in range(1, 11)] # WRONG!
練習(xí)
如果list中既包含字符串,又包含整數(shù),由于非字符串類型沒有l(wèi)ower()方法,所以列表生成式會報錯。使用內(nèi)建的isinstance函數(shù)可以判斷一個變量是不是字符串。請修改列表生成式,通過添加if語句保證列表生成式能正確地執(zhí)行:
# -*- coding: utf-8 -*- L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [s.lower() for s in L1 if isinstance(s,str)]
生成器
如果列表元素可以按照某種算法推算出來,則可以在循環(huán)的過程中不斷推算出后續(xù)的元素,這樣就不必創(chuàng)建完整的list,從而節(jié)省大量的空間。在Python中,這種一邊循環(huán)一邊計算的機制,稱為生成器:generator。
創(chuàng)建generator的方法:
1.把一個列表生成式的[]改成(),就創(chuàng)建了一個generator,創(chuàng)建之后通過next可以得到下一個元素,或者通過for循環(huán)迭代(generator也是可迭代對象)
# 生成一個迭代器 g = (x * x for x in range(10)) # 獲得下一個元素 next(g) # 0 # for循環(huán)遍歷 for n in g: print(n)
2.使用yield,如果一個函數(shù)定義中包含yield關(guān)鍵字,那么這個函數(shù)就不再是一個普通函數(shù),而是一個generator函數(shù),調(diào)用一個generator函數(shù)將返回一個generator
generator函數(shù)在每次調(diào)用next()的時候執(zhí)行,遇到y(tǒng)ield語句返回,再次執(zhí)行時從上次返回的yield語句處繼續(xù)執(zhí)行
調(diào)用generator函數(shù)時,首先要生成一個generator對象,然后用next()函數(shù)不斷獲得下一個返回值
# 斐波拉契數(shù)列的生成 def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' # 調(diào)用 f = fib(6) next(f) # for循環(huán)調(diào)用 while True: try: x = next(g) print('g:', x) except StopIteration as e: print('Generator return value:', e.value) break
用for循環(huán)調(diào)用generator時,拿不到generator的return語句的返回值。如果想要拿到返回值,必須捕獲StopIteration錯誤,返回值包含在StopIteration的value中
練習(xí)
楊輝三角定義如下:
1 / \ 11 / \ / \ 121 / \ / \ / \ 1331
把每一行看做一個list,試寫一個generator,不斷輸出下一行的list:
# -*- coding: utf-8 -*- def triangles(): levellist = [1] n = 1 while (n<=100): yield levellist newlist = levellist.copy() if (n>=2): for i in range(0,n-1): newlist[i+1] = levellist[i] + levellist[i+1] levellist = newlist.copy() n = n + 1 levellist.append(1) return 'done'
迭代器
可以被next()函數(shù)調(diào)用并不斷返回下一個值的對象稱為迭代器:Iterator。
可以使用isinstance()判斷一個對象是否是Iterator對象:
生成器都是Iterator對象,但list、dict、str雖然是Iterable,卻不是Iterator。把list、dict、str等Iterable變成Iterator可以使用iter()函數(shù)
為什么list、dict、str等數(shù)據(jù)類型不是Iterator?
因為Python的Iterator對象表示的是一個數(shù)據(jù)流,Iterator對象可以被next()函數(shù)調(diào)用并不斷返回下一個數(shù)據(jù),直到?jīng)]有數(shù)據(jù)時拋出StopIteration錯誤??梢园堰@個數(shù)據(jù)流看做是一個有序序列,但我們卻不能提前知道序列的長度,只能不斷通過next()函數(shù)實現(xiàn)按需計算下一個數(shù)據(jù),所以Iterator的計算是惰性的,只有在需要返回下一個數(shù)據(jù)時它才會計算。
Iterator甚至可以表示一個無限大的數(shù)據(jù)流,例如全體自然數(shù)。而使用list是永遠不可能存儲全體自然數(shù)的。
Python的for循環(huán)本質(zhì)上就是通過不斷調(diào)用next()函數(shù)實現(xiàn)的
以上就是Python高級特性之切片迭代列表生成式及生成器詳解的詳細內(nèi)容,更多關(guān)于python高級特性詳解的資料請關(guān)注本站其它相關(guān)文章!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。