您好,登錄后才能下訂單哦!
這篇文章主要介紹Python生成器、裝飾器、遞歸的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
1、Python生成器表達式
1)、Python生成器表達式
語法格式:
(expr for iter_var in iterable)
(expr for iter_var in iterable ifcond_expr)
2)、自定義生成器
函數中使用yield,會返回一個生成器對象。yieldx
生成器使用示例:
In [1]:list((i**2 for i in range(1,11))) Out[1]:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] In [2]:def genNum(x): ...: y = 0 ...: while y <= x: ...: yield y ...: y += 1 In [3]: g1= genNum(4) In [4]:type(g1) Out[4]:generator In [5]:g1.next() Out[5]:0 In [6]:g1.next() Out[6]:1 In [7]:g1.next() Out[7]:2 In [8]:g1.next() Out[8]:3 In [9]:g1.next() Out[9]:4 In [10]:g1.next() -------------------------------------------------- StopIteration Traceback (most recent call last) in() ----> 1g1.next() StopIteration: In [11]:def genNum(n): ....: i = 1 ....: while i <= n: ....: yield i ** 2 ....: i += 1 In [12]:g1 = genNum(20) In [13]:for i in g1: ....: print i, ....: 1 4 9 1625 36 49 64 81 100 121 144 169 196 225 256 289 324 361400
2、Python裝飾器
1)、裝飾器本身是一個函數,用于裝飾其它函數;
2)、功能:增強被裝飾函數的功能;
裝飾器一般接受一個函數對象作為參數,以對其進行增強
例1:裝飾器使用示例
In [1]:def decorater(func): ...: def wrapper(): ...: print "Just a Decorater!" ...: func() ...: raw_input('Please Input your name:') ...: return wrapper ...: In [2]:@decorater ...:def show(): ...: print "I am from China." ...: In [3]:show() Just aDecorater! I am fromChina. PleaseInput your name:Fieldyang
例2:對能夠傳入參數的函數進行裝飾
In [1]:def decorater(func): ...: def wrapper(x): ...: print "Just a Decorater!" ...: func(x) ...: raw_input('Please Input your name:') ...: return wrapper ...: In [2]:@decorater ...:def show(x): ...: print "I am from China.%s" %x ...: In [3]:show('how are you ?') Just aDecorater! I am fromChina.how are you ? PleaseInput your name:Fieldyang
3、Python遞歸
遞歸需要邊界條件,遞歸前進段和遞歸返回段;
10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 *1 10 * (10-1)* ((10-1)-1)* ...
遞歸函數使用示例:
In [1]:def recursion(n): ...: if n <= 1: return 1 ...: else: return n * recursion(n-1) ...:
#遞歸函數相當于如下過程:
In [2]: recursion(3) = 3 * recursion(2)= 3 * 2 *recursion(1)=3*2*1 KeyboardInterrupt In [3]:recursion(3) Out[3]:6 In [4]:recursion(4) Out[4]:24 In [5]:recursion(5) Out[5]:120 In [6]:recursion(10) Out[6]:3628800
以上是“Python生成器、裝飾器、遞歸的示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。