数据之路 Day5 - Python基础5
1.迭代
通過for循環(huán)來遍歷這個list或tuple,這種遍歷我們稱為迭代(Iteration)
# 遍歷字符串 for x in 'hello':print(x)# 遍歷列表 lt = [1, 2, 3] for i in lt:# 手動獲取下標print(i, lt.index(i))# 遍歷列表,可以直接使用下標 for index, value in enumerate(lt):print(index, value)# 遍歷字典 d = {'a': 'apple', 'b': 'banana', 'c': 'cat', 'd': 'dog'} for k in d:# 默認遍歷的是鍵,值需要單獨獲取print(k, d[k])for k,v in info.items():print('%s is %s'%(k,v))# for k, v in d.items(): # 上下兩個式子等價 for k, v in dict.items(d):print(k, v)2.列表生成式
例1:生成[1x1, 2x2, 3x3, ..., 10x10]# 方法一:循環(huán) L = [] for x in range(1, 11):L.append(x * x)# 方法二:列表生成式 [x * x for x in range(1, 11)]>>>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]例2for + if 判斷 [x * x for x in range(1, 11) if x % 2 == 0]>>>[4, 16, 36, 64, 100]例3 使用兩層循環(huán),可以生成全排列: [m + n for m in 'ABC' for n in 'XYZ']>>>['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']例4 for循環(huán)對dict的items()可以同時迭代key和value: d = {'x': 'A', 'y': 'B', 'z': 'C' } for k, v in d.items():print(k, '=', v)>>> y = Bx = Az = C列表生成式,使用兩個變量來生成list: d = {'x': 'A', 'y': 'B', 'z': 'C' } [k + '=' + v for k, v in d.items()]>>> ['y=B', 'x=A', 'z=C']把一個list中所有的字符串變成小寫: L = ['Hello', 'World', 'IBM', 'Apple'] [s.lower() for s in L]>>> ['hello', 'world', 'ibm', 'apple']3.生成器
Python中,一邊循環(huán)一邊計算的機制,稱為生成器:generator
generator創(chuàng)建:
# 方法一:將一個列表生成式的[]改成() L = [x * x for x in range(10)] # 列表生成式 g = (x * x for x in range(10)) # 生成器 generator的下一個返回值,通過next()函數(shù)獲得 generator保存的是算法,每次調(diào)用next(g),就計算出g的下一個元素的值,直到計算到最后一個元素,沒有更多的元素時,拋出StopIteration的錯誤為避免StopIteration的錯誤 g = (x * x for x in range(10)) for n in g:print(n)# 方法二 def fib(max):n, a, b = 0, 0, 1while n < max:print(b)a, b = b, a + b # 賦值語句n = n + 1return 'done'斐波拉契數(shù)列的推算規(guī)則,邏輯類似generator 要把fib函數(shù)變成generator,只需要把print(b)改為yield b def fib(max):n, a, b = 0, 0, 1while n < max:yield ba, b = b, a + bn = n + 1return 'done'generator和函數(shù)的執(zhí)行流程不一樣。
函數(shù)是順序執(zhí)行,遇到return語句或者最后一行函數(shù)語句就返回。
generator,在每次調(diào)用next()的時候執(zhí)行,遇到y(tǒng)ield語句返回,再次執(zhí)行時從上次返回的yield語句處繼續(xù)執(zhí)行。 循環(huán)過程中不斷調(diào)用yield,就會不斷中斷,
因此需要要給循環(huán)設(shè)置一個條件來退出循環(huán),否則會產(chǎn)生一個無限數(shù)列。
for循環(huán)調(diào)用generator時,發(fā)現(xiàn)拿不到generator的return語句的返回值。 如果想要拿到返回值,必須捕獲StopIteration錯誤,返回值包含在StopIteration的value中。
g = fib(6) while True:try:x = next(g)print('g:', x)except StopIteration as e:print('Generator return value:', e.value)break>>> g: 1g: 1g: 2g: 3g: 5g: 8Generator return value: done4.迭代器
可以被next()函數(shù)調(diào)用并不斷返回下一個值的對象稱為迭代器:Iterator。
凡是可作用于for循環(huán)的對象都是Iterable類型;
凡是可作用于next()函數(shù)的對象都是Iterator類型,它們表示一個惰性計算的序列;
集合數(shù)據(jù)類型如list、dict、str等是Iterable但不是Iterator,不過可以通過iter()函數(shù)獲得一個Iterator對象。
Python的for循環(huán)本質(zhì)上就是通過不斷調(diào)用next()函數(shù)實現(xiàn): for x in [1, 2, 3, 4, 5]:pass實際上完全等價于:# 首先獲得Iterator對象: it = iter([1, 2, 3, 4, 5]) # 循環(huán): while True:try:# 獲得下一個值:x = next(it)except StopIteration:# 遇到StopIteration就退出循環(huán)break5.裝飾器
# -*- coding:gbk -*- '''示例1: 使用語法糖@來裝飾函數(shù),相當于“myfunc = deco(myfunc)” 但發(fā)現(xiàn)新函數(shù)只在第一次被調(diào)用,且原函數(shù)多調(diào)用了一次'''def deco(func):print("before myfunc() called.")func()print(" after myfunc() called.")return func@deco #@deco和myfunc = deco(myfunc)其實是完全等價的 def myfunc():print(" myfunc() called.")myfunc() myfunc()# 裝飾器被調(diào)用 # -*- coding:gbk -*- '''示例2: 使用內(nèi)嵌包裝函數(shù)來確保每次新函數(shù)都被調(diào)用, 內(nèi)嵌包裝函數(shù)的形參和返回值與原函數(shù)相同,裝飾函數(shù)返回內(nèi)嵌包裝函數(shù)對象'''def deco(func):def _deco():print("before myfunc() called.")func()print(" after myfunc() called.")# 不需要返回func,實際上應(yīng)返回原函數(shù)的返回值return _deco@deco def myfunc():print(" myfunc() called.")return 'ok'myfunc() myfunc()# 對帶參數(shù)的函數(shù)進行裝飾 # -*- coding:gbk -*- '''示例5: 對帶參數(shù)的函數(shù)進行裝飾, 內(nèi)嵌包裝函數(shù)的形參和返回值與原函數(shù)相同,裝飾函數(shù)返回內(nèi)嵌包裝函數(shù)對象'''def deco(func):def _deco(a, b):print("before myfunc() called.")ret = func(a, b)print(" after myfunc() called. result: %s" % ret)return retreturn _deco@deco def myfunc(a, b):print(" myfunc(%s,%s) called." % (a, b))return a + bmyfunc(1, 2) myfunc(3, 4)# 讓裝飾器帶參數(shù) # -*- coding:gbk -*- '''示例7: 在示例4的基礎(chǔ)上,讓裝飾器帶參數(shù), 和上一示例相比在外層多了一層包裝。 裝飾函數(shù)名實際上應(yīng)更有意義些'''def deco(arg):def _deco(func):def __deco():print("before %s called [%s]." % (func.__name__, arg))func()print(" after %s called [%s]." % (func.__name__, arg))return __decoreturn _deco@deco("mymodule") def myfunc():print(" myfunc() called.")@deco("module2") def myfunc2():print(" myfunc2() called.")myfunc() myfunc2()轉(zhuǎn)載于:https://www.cnblogs.com/Iceredtea/p/9691744.html
總結(jié)
以上是生活随笔為你收集整理的数据之路 Day5 - Python基础5的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 王者荣耀恋人系统在哪
- 下一篇: python3.6入门到高阶(全栈)