床長人工智能教程免費擴(kuò)展212
朋友們,如需轉(zhuǎn)載請標(biāo)明出處:[https://blog.csdn.net/jiangjunshow](https://blog.csdn.net/jiangjunshow)
聲明:在人工智能技術(shù)教學(xué)期間,不少學(xué)生向我提一些python相關(guān)的問題,所以為了讓同學(xué)們掌握更多擴(kuò)展知識更好地理解AI技術(shù),我讓助理負(fù)責(zé)分享這套python系列教程,希望能幫到大家!由于這套python教程不是由我所寫,所以不如我的AI技術(shù)教學(xué)風(fēng)趣幽默,學(xué)起來比較枯燥;但它的知識點還是講到位的了,也值得閱讀!想要學(xué)習(xí)AI技術(shù)的同學(xué)可以點擊跳轉(zhuǎn)到我的[教學(xué)網(wǎng)站](https://www.captainai.net/csdn)。PS:看不懂本篇文章的同學(xué)請先看前面的文章,循序漸進(jìn)每天學(xué)一點就不會覺得難了!
函數(shù)式編程的意思就是對序列應(yīng)用一些函數(shù)。例如,下面這個filter的調(diào)用實現(xiàn)了從一個序列中挑選出大于0的元素。
```
>>>list(range(-5,5))? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # An iterator in 3.0
[-5,-4,-3,-2,-1,0,1,2,3,4]
>>>list(filter((lambda x: x > 0),range(-5,5)))? ? ?# An iterator in 3.0
[1,2,3,4]
```
這個函數(shù)也能夠用一個for循環(huán)來等效實現(xiàn),但是它也是內(nèi)置的函數(shù),所以運行比for循環(huán)要快。
```
>>>res = []
>>> for x in range(-5,5):
...? ? ?if x > 0:
...? ? ? ? res.append(x)
...
>>>res
[1,2,3,4]
```
reduce在Python 2.6中只是一個簡單的內(nèi)置函數(shù),但是在Python 3.0中則位于functools模塊中,要更復(fù)雜一些。這里是兩個reduce調(diào)用,計算了在一個列表中所有元素加起來的和以及乘起來的乘積。
```
>>>from functools import reduce? ? ? ? ? ? ? ? ? ? # Import in 3.0,not in 2.6
>>>reduce((lambda x,y: x + y),[1,2,3,4])
10
>>>reduce((lambda x,y: x * y),[1,2,3,4])
24
```
下面是一個對第一個調(diào)用的for循環(huán)的等效實現(xiàn)。
```
>>>L = [1,2,3,4]
>>>res = L[0]
>>>for x in L[1:]:
...? ? res = res + x
...
>>>res
10
```
編寫自己的reduce版本實際上相當(dāng)簡單:
```
>>>def myreduce(function,sequence):
...? ? tally = sequence[0]
...? ? for next in sequence[1:]:
...? ? ? ? tally = function(tally,next)
...? ? return tally
...
>>>myreduce((lambda x,y: x + y),[1,2,3,4,5])
15
>>>myreduce((lambda x,y: x * y),[1,2,3,4,5])
120
```
內(nèi)置的operator模塊提供了一些函數(shù),它們使用起來是很方便的(要了解關(guān)于這一模塊的更多內(nèi)容,請參閱Python的庫手冊)。
```
>>>import operator,functools
>>>functools.reduce(operator.add,[2,4,6])? # Function-based +
12
>>>functools.reduce((lambda x,y: x + y),[2,4,6])
12
```