內(nèi)置函數(shù)
內(nèi)置函數(shù):
作用域相關(guān):
locals()
更新并返回表示當(dāng)前本地變量的字典。在函數(shù)塊而不是類塊中調(diào)用 locals() 時會返回自由變量
globals()
返回表示當(dāng)前全局變量的字典。
其它:
eval
eval(expression, globals=None, locals=None)
實(shí)參是一個字符串,以及可選的 globals 和 locals變量。
print(eval('1+2*5'))
>>>11
exec
exec(object[, globals[, locals]])
這個函數(shù)支持動態(tài)執(zhí)行 Python 代碼。
exec("print(eval('1+2*5'))")
>>>11
compile
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
將 source 編譯成代碼編譯。
參數(shù)source:字符串或者AST(Abstract Syntax Trees)對象。即需要動態(tài)執(zhí)行的代碼段。
filename 實(shí)參需要是代碼讀取的文件名
mode 實(shí)參指定了編譯代碼必須用的模式。
可選參數(shù) flags 和 dont_inherit 控制在編譯 source 時要用到哪個 future 語句。
code = 'for i in range(10):print(i)' com = compile(code,'','exec') exec(com) 0 1 2 3 4 5 6 7 8 9
input([prompt])
如果存在 prompt 實(shí)參,則將其寫入標(biāo)準(zhǔn)輸出,末尾不帶換行符。
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
將 objects 打印到 file 指定的文本流,以 sep 分隔并在末尾加上 end。
import time
for i in range(101):
print('\r%s%%'%i,end='')
time.sleep(0.1)
type(o)
返回變量o的數(shù)據(jù)類型
id(object)
返回對象的“標(biāo)識值”(內(nèi)存地址)。
hash(o)
o是參數(shù),返回一個可hash變量的哈希值,不可hash的變量被hash之后會報錯。
callable(object)
如果實(shí)參 object 是可調(diào)用的,返回 True,否則返回 False。
dir([object])
如果沒有實(shí)參,則返回當(dāng)前本地作用域中的名稱列表。
print(dir(list)) #查看列表的內(nèi)置方法 print(dir(int)) #查看整數(shù)的內(nèi)置方法
和數(shù)字相關(guān)
數(shù)字——數(shù)據(jù)類型相關(guān):bool,int,float,complex
數(shù)字——進(jìn)制轉(zhuǎn)換相關(guān):bin,oct,hex
數(shù)字——數(shù)學(xué)運(yùn)算:abs,divmod,min,max,sum,round,pow
數(shù)據(jù)集合——字典和集合:dict,set,frozenset
數(shù)據(jù)集合:len,sorted,enumerate,all,any,zip,filter,map
filter(function, iterable)
用 iterable 中函數(shù) function 返回真的那些元素,構(gòu)建一個新的迭代器。
def func(x):
return x%2==0
lst = filter(func,range(10))
print(list(lst))
[0, 2, 4, 6, 8]
map(function, iterable, ...)
產(chǎn)生一個將 function 應(yīng)用于迭代器中所有元素并返回結(jié)果的迭代器。
def func(x):
return x*2
lst = map(func,range(10))
print(list(lst))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
匿名函數(shù):

res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
print(i)
輸出
25
16

浙公網(wǎng)安備 33010602011771號