標籤:python 內建函數
內建函數
例:如果返回數位絕對值 ,寫函數是非常不方便的[[email protected] tools]# python fa.py 10[[email protected] tools]# cat fa.py #!/usr/bin/pythondef a(x): if x < 0 : return -x return x n = a(-10)print n
#協助查看#
>>> help(len)
用法: help(函數名)
abs() 返回絕對值
>>> abs(-10)10
max()返回最大值 , min()返回最小值
>>> l=[1,4,7,12,555,66,]>>> min(l)1>>> max(l)555
len() 擷取字串長度
>>> s = ‘konglingchao‘>>> len(s)12
divmod() 求商,求餘 用法:divmod(除數,被除數)
>>> divmod(10,2)(5, 0)
pow() 次方運算 用法: pow(數1,數2,/(數3)) 數3可有可無
>>> pow(3,3)27>>> pow(3,3,2)1
round()返回浮點數
>>> round(1112)1112.0
callable()測試函數是否被定義
>>> callable(min)True #函數定義返回True>>> callable(f)Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name ‘f‘ is not defined #函數未被定義>>> f=100 #f是一個變數>>> callable(f)False #返回True
isinstance()
>>> print l[1, 4, 7, 12, 555, 66]>>> print f<function f at 0x1a1e320>>>> type(f)<type ‘function‘>>>> type(l)<type ‘list‘> >>> if type(l) ==type([]):... print ‘ok‘... ok #判斷是否為列表使用isinstance 判斷某一個物件類型>>> isinstance(l,int)False>>> isinstance(l,str)False>>> isinstance(l,list)True
cmp ()字串比較
>>> cmp("7","7")0>>> cmp("7","m")-1>>> cmp("7","6")1
range()快速產生序列
>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
xrange() 可以 理解為對象,效率比range高
>>> x = xrange(10)>>> print xxrange(10)
資料轉換類型的函數:
int() 整數
long() 長整形
float() 浮點型
complex() 複數型
str()
list()
tuple()
>>> L=[1,2,3,4]>>> tuple(l)(1, 4, 7, 12, 555, 66)
注意: 資料轉換要有選擇性的轉換
>>> s=‘hello‘>>> int(s)Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: ‘hello‘>>> s=‘123‘>>> type(s)<type ‘str‘>>>> int(s)123
string 函數 :功能只限於對字串的操作
#查看協助要 加上 函數的類別:>>> help(str.replace)
str.capitalize() :首字母大寫
>>> s=‘hello‘>>> str.capitalize(s)‘Hello‘>>> s‘hello word‘>>> s.capitalize() #s是字串裡的對象,s調用capitalize函數‘Hello word‘
str.replace() :替換,(可以指定替換次數)
>>> s.replace(‘hello‘,‘good‘)‘good word‘>>> s‘hello word‘#這裡的good word 只是一個傳回值,並沒有將資料直接改變>>> ss=‘12121212121212‘>>> ss.replace(‘1‘,‘xxxxx‘)‘xxxxx2xxxxx2xxxxx2xxxxx2xxxxx2xxxxx2xxxxx2‘>>> ss.replace(‘1‘,‘xxxxx‘,1) #指定替換的次數‘xxxxx2121212121212‘
str.split() :切割 str.split(“參數1:切割服”,“參數2=切割次數”)
>>> ip="192.168.1.2"
>>> ip.split(‘.‘)
[‘192‘, ‘168‘, ‘1‘, ‘2‘]
>>> ip.split(‘.‘,2)
[‘192‘, ‘168‘, ‘1.2‘]
#######################
通過匯入模組調用方法
>>> import string >>> help(string.replace)>>> s‘hello word‘>>> string.replace(s,‘hello‘,‘good‘)‘good word‘
#####################################
序列處理函數
len()
max()
min()
#使用序列函數求數位長度是無法使用的!!!!!
>>> len(123)Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: object of type ‘int‘ has no len()>>>
filter (參數1:函數,參數2:序列)
Help on built-in function filter in module __builtin__:
filter(...)
filter(function or None, sequence) -> list, tuple, or string
#函數 或者 #空 序列
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list.
範例:
>>> def f(x):... if x>5:... return True... >>> f(10)True>>> f(3)>>> l=range(10)>>> l[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> filter(f,l)[6, 7, 8, 9]# f 函數作用於列表l
zip、map()列表遍曆
>>> name=[‘milo‘,‘zou‘,‘tom‘]>>> age=[20,30,40]>>> tel=[‘133‘,‘144‘,‘155‘]>>> zip(name,age,tel)[(‘milo‘, 20, ‘133‘), (‘zou‘, 30, ‘144‘), (‘tom‘, 40, ‘155‘)]#並行遍曆>>> map(None,name,age,tel)[(‘milo‘, 20, ‘133‘), (‘zou‘, 30, ‘144‘), (‘tom‘, 40, ‘155‘)]>>> test=[‘a‘,‘b‘]#如果其中一個列表的值少於其它列表,它會取最短的列表進行遍曆;>>> zip(name,age,tel,test)[(‘milo‘, 20, ‘133‘, ‘a‘), (‘zou‘, 30, ‘144‘, ‘b‘)]如果換為map遍曆,它會將某一列表缺少的值用None填充。>>> map(None,name,age,tel,test)[(‘milo‘, 20, ‘133‘, ‘a‘), (‘zou‘, 30, ‘144‘, ‘b‘), (‘tom‘, 40, ‘155‘, None)]#此處的None也可以變為函數,把後面的值進行運算。>>> a=[1,4,6,]>>> b=[7,8,9]>>> map(None,a,b)[(1, 7), (4, 8), (6, 9)]>>> def mf(x,y):... print x*y... >>> map(mf,a,b)73254[None, None, None]
reduce()遞迴 運算
>>> def f(x,y):... return x+y... >>> l=(range(1,101))>>> reduce(f,l)5050或者使用匿名函數>>> reduce(lambda x,y:x+y,l)5050
本文出自 “思想大於技術” 部落格,謝絕轉載!
python 基礎 學習 內建函數