6.3、高階函數、常用內置函數
阿新 • • 發佈:2018-02-03
lec for from calc 表達式 類型 文件中 add log
高階函數:
- 允許將函數作為參數傳入另一個函數;
- 允許返回一個函數。
#返回值為函數的函數 sum=lambda x,y:x+y sub=lambda x,y:x-y calc_dict={"+":sum,"-":sub} def calc(x): return calc_dict[x] print(calc(‘-‘)(5,6)) print(calc(‘+‘)(5,6)) #參數有函數的函數 filter(lambda x:x>5,range(20))
常用內置函數:
- abs(x):求絕對值
- range([start], stop[, step]) :產生一個序列,默認從0開始
- 註意:返回的不是一個list對象
>>> print(range(20)) range(0, 20) >>> type(range(20)) <class ‘range‘> >>> isinstance(range(20),Iterable)#########是一個可叠代對象 True >>> from collections import Iterator >>> isinstance(range(20),Iterator)#不是一個叠代器對象 False
- oct(x)
將一個數字轉化為8進制 - hex(x)
將整數x轉換為16進制字符串 - bin(x)
將整數x轉換為二進制字符串
>>> oct(8) ‘0o10‘ >>> hex(8) ‘0x8‘ >>> bin(8) ‘0b1000‘
- chr(i):返回整數i對應的Unicode字符
- ord(x):將字符轉換成對應的Unicode編址
>>> ord(‘中‘) 20013 >>> chr(20013) ‘中‘
- enumerate(sequence [, start = 0]):返回一個可枚舉的對象,該對象的next()方法將返回一個tuple
for i, value in enumerate([‘A‘, ‘B‘, ‘C‘]): print(i, value)
- iter(o[, sentinel]) :生成一個對象的叠代器,第二個參數表示分隔符
from collections import Iterator #可以被next()函數調用並不斷返回下一個值的對象稱為叠代器:Iterator。 print(isinstance([],Iterator)) print(isinstance(iter([]),Iterator))
- sorted(iterable[, cmp[, key[, reverse]]]) 對可叠代對象進行排序
>>> l=[8,7,6,5,4,3,2,1] >>> sorted(l) [1, 2, 3, 4, 5, 6, 7, 8]
- cmp(x, y) :如果x < y ,返回負數;x == y, 返回0;x > y,返回正數
- all(iterable)
1、可叠代對象中的元素都為真的時候為真
2、特別的,可叠代對象若為空返回為True
>>> l=[] >>> all(l) True >>> l=[1,2,3,4,5] >>> all(l) True >>> l=[1,2,3,4,5,0] >>> all(l) False
- any(iterable)
1、可叠代對象中的元素有一個為真的時候為真
2、特別的,可叠代對象若為空返回為False
>>> l=[] >>> any(l) False >>> l=[0,0,0,0] >>> any(l) False >>> l=[0,0,0,0,5] >>> any(l) True >>>
- eval(expression [, globals [, locals]]) :計算表達式expression的值
>>> str1="3+4" >>> eval(str1) 7
- exec(object[, globals[, locals]]):執行儲存在字符串或文件中的 Python 語句
>>> str1="print(‘hello world‘)" >>> exec(str1) hello world
- compile(source, filename, mode[, flags[, dont_inherit]])
- 將source編譯為代碼或者AST對象。代碼對象能夠通過exec語句來執行或者eval()進行求值。
1、參數source:字符串或者AST(Abstract Syntax Trees)對象。
2、參數 filename:代碼文件名稱,如果不是從文件讀取代碼則傳遞一些可辨認的值。
3、參數model:指定編譯代碼的種類。可以指定為 ‘exec’,’eval’,’single’。
4、參數flag和dont_inherit:這兩個參數暫不介紹
str1 = "print(‘hello world‘)" c2 = compile(str1,‘‘,‘exec‘) exec(c2) str2="3+4" c3=compile(str2,‘‘,‘eval‘) a=eval(c3) print(a)
- id(object) :函數用於獲取對象的內存地址
>>> id(str1) 1514678732384 >>> str2=str1 >>> id(str2) 1514678732384
- isinstance(object, classinfo):判斷object是否是class的實例
>>> isinstance(1,int) True >>> isinstance(1.0,int) False
- len(s) :返回長度(ascll格式的返回字節數,unicode返回字符數/或元素個數)
>>> a=b‘abc‘ >>> len(a) 3 >>> b="我愛中國" >>> len(b) 4 >>> c=[1,2,3,4] >>> len(c) 4
- repr(object) :將對象轉化為供解釋器讀取的形式,實質是返回一個對象的 string 格式
>>> c=[1,2,3,4] >>> repr(c) ‘[1, 2, 3, 4]‘ >>> d={1:2,2:3,3:4} >>> repr(d) ‘{1: 2, 2: 3, 3: 4}‘
- type(object) :返回該object的類型
>>> type(1) <class ‘int‘> >>> type("123") <class ‘str‘> >>> type((1,2,3)) <class ‘tuple‘>
6.3、高階函數、常用內置函數