what's the python之內置函數


what's the 內置函數?

  內置函數,內置函數就是python本身定義好的,我們直接拿來就可以用的函數。(python中一共有68中內置函數。)

 

    Built-in Functions    
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()  

 

下面我們由作用不同分別進行詳述:(字體加粗的為重點要掌握的)

與作用域相關:global和local

  • global——獲取全局變量的字典
  • local——獲取執行本方法所在命名空間內的局部變量的字典

 

str類型代碼的執行:eval、exec、compile

  • eval()——將字符串類型的代碼執行並返回結果
  • exec()——將字符串類型的代碼執行但不返回結果
  • compile ——將字符串類型的代碼編譯。代碼對象能夠通過exec語句來執行或者eval()進行求值

 

>>> #流程語句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec') >>> exec (compile1) 1
3
5
7
9


>>> #簡單求值表達式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval') >>> eval(compile2) >>> #交互語句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single') >>> name #執行前name變量不存在
Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> name NameError: name 'name' is not defined >>> exec(compile3) #執行時顯示交互命令,提示輸入
please input your name:'pythoner'
>>> name #執行后name變量有值
"'pythoner'"
View Code

 

與數字相關的:

 

  • 數字——數據類型相關:bool,int,float,complex
  • 數字——進制轉換相關:bin,oct,hex
  • 數字——數學運算:abs(輸出為數字的絕對值),divmod(使用方法即divmod(數字1,數字2),輸出為(數字1整除數字2后得到的數,余數)),min,max,sum,round(精確的功能),pow(pow的使用方法即pow(數字1,數字2),數字1**數字2,即次方的形式
print(divmod(7,3))#(2,1)

print(round(3.14159,2))#3.14
f = 4.197937590783291932703479  #-->二進制轉換的問題
print(f)#4.197937590783292
View Code

 

 

與數據結構有關:

  • 序列——列表和元組相關的:list和tuple
  • 序列——字符串相關的:str,format,bytes,bytesarry,memoryview,ord(ord與chr互為倒數,不過這不需要掌握),chr(返回表示Unicode代碼點為整數i的字符的字符串。例如,chr(97)返回字符串'a',同時 chr(8364)返回字符串'€'),ascii,repr
  • 序列:reversed(用l.reverse,將原列表翻轉並賦值,用list(reversed(l)只是將原列表翻轉看看,不改變原列表的值也就是說不覆蓋),slice(切片的功能)
  • 數據集合——字典和集合:dict,set,frozenset
  • 數據集合:len,sorted(排序功能),enumerate(將一個列表的元素由“索引 值”的形式一一解包出來),all,any,zip,filter(一種過濾的功能),map(一種迭代的功能)
l2 = [1,3,5,-2,-4,-6] print(sorted(l2,key=abs,reverse=True))#[-6, 5, -4, 3, -2, 1]
print(sorted(l2))#[-6, -4, -2, 1, 3, 5]
print(l2)#[1, 3, 5, -2, -4, -6]
 l = ['a','b'] for i,j in enumerate(l,1): print(i,j) #1 a
  2 b L = [1,2,3,4] def pow2(x): return x*x l=map(pow2,L) print(list(l)) # 結果:
[1, 4, 9, 16] def is_odd(x): return x % 2 == 1 l=filter(is_odd, [1, 4, 6, 7, 9, 12, 17]) print(list(l)) # 結果:
[1, 7, 9, 17]
View Code

 

其他:

 

 

輸入輸出:input(),print()

  • input——與用戶交互用的
  • print——打印
#print的源碼分析:
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    """ print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) file: 默認是輸出到屏幕,如果設置為文件句柄,輸出到文件 sep: 打印多個值之間的分隔符,默認為空格 end: 每一次打印的結尾,默認為換行符 flush: 立即把內容輸出到流文件,不作緩存 """


#有關進度條打印的小知識
import time import sys for i in range(0,101,2): time.sleep(0.1) char_num = i//2      #打印多少個#
     per_str = '%s%% : %s\n' % (i, '*' * char_num) if i == 100 else '\r%s%% : %s'%(i,'*'*char_num) print(per_str,end='', file=sys.stdout, flush=True) 復制代碼
View Code
  • callable——查看參數是否能被調用
def func():pass
print(callable(func))  #參數是函數名,可調用,返回True
print(callable(123))   #參數是數字,不可調用,返回False
  • dir——可用於查看一個數據類型的內置方法,類似於help,是一種幫助

 

附:可供參考的有關所有內置函數的文檔https://docs.python.org/3/library/functions.html#object

 

 

     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM