python高階技能

山谷來客發表於2017-11-12
1、匿名函式:lambda¶
In [1]:
f=lambda x,y,z:x+y+z
f(2,3,4)
Out[1]:
9
In [2]:
L=[lambda x:x**2,
  lambda x: x**3,
  lambda x:x**4]
for f in L:
    print(f(2))
4
8
16
In [3]:
import sys
showall=lambda x:[sys.stdout.write(line) for line in x] #在lambda中進行print
t=showall(('bright\n', 'side\n', 'of\n', 'life\n')) 
bright
side
of
life


2、在序列重對映函式:map¶
In [4]:
counters=[1,2,3,4]
def inc(x):return x+10
map(inc,counters)
#說明:map函式對一個序列物件中的每一個元素應用被傳入的函式,並且返回一個包含了所有函式呼叫結果的一個列表
Out[4]:
[11, 12, 13, 14]
In [5]:
pow(2,3)
Out[5]:
8
In [6]:
map(pow,[1,2,3],[2,3,4])
Out[6]:
[1, 8, 81]


3、函數語言程式設計工具:filter和reduce¶
In [7]:
range(-5,5)
Out[7]:
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
In [8]:
filter((lambda x:x>0), range(-5,5))
Out[8]:
[1, 2, 3, 4]
In [9]:
reduce((lambda x,y:x+y),[1,2,3,4])
Out[9]:
10
In [10]:
reduce((lambda x,y:x*y),[1,2,3,4])
Out[10]:
24
In [11]:
reduce((lambda x,y:x*y),[1,2,3,4])
Out[11]:
24
In [ ]:
 


4、python3的reduce及如何檢視python版本資訊¶
In [1]:
import platform 
In [2]:
platform.python_version()
Out[2]:
'3.5.2'
In [3]:
from functools import reduce
In [4]:
reduce((lambda x,y:x+y),[1,2,3,4])
Out[4]:
10
In [5]:
import sys
print(sys.version)
3.5.2 |Anaconda 4.2.0 (64-bit)| (default, Jul  5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)]



相關文章