python學習筆記11-python內置函數

python學習筆記11-python內置函數

一、查看python的函數介紹:

https://docs.python.org/2/library/

二、python內置函數

1、abs獲取絕對值:

通過python官網查看abs

  • abs(x)
  • Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.

通過help查看abs

In [20]: help(abs)

Help on built-in function abs in module __builtin__:

abs(…)

    abs(number) -> number    #返回一個number

    Return the absolute value ofthe argument. #返回絕對值

(END) 

abs實例:

In [14]: def fun(x):      ...:     if x < 0:      ...:         return -x      ...:     return x      ...:   In [15]: fun(10)  Out[15]: 10  In [16]: fun(-10)  Out[16]: 10  In [17]: abs(-10)  Out[17]: 10  In [18]: abs(10)  Out[18]: 10  In [19]: abs(-100)  Out[19]: 100

2、max()min()列表的最大值和最小值

In [22]: max([1,2,3,4,5])  Out[22]: 5  In [23]: min([1,2,3,4,5])  Out[23]: 1  Help on built-in function max in module __builtin__:  max(...)      max(iterable[, key=func]) -> value  #可迭代的對象      max(a, b, c, ...[, key=func]) -> value          With a single iterable argument, return its largest item.#返回最大的參數      With two or more arguments, return the largest argument.  In [26]: max('hsdhsjd','5687','12') #最長的一個  Out[26]: 'hsdhsjd'

3、獲取長度len()

In [27]: s='1234'  In [28]: len(s)  #取字元創的長度  Out[28]: 4  help(len)  Help on built-in function len in module __builtin__:  len(...)      len(object) -> integer    #處理對象,返回整數       Return the number of items of a sequence or collection.  In [31]: len([1,2])#取列表的元素個數,2個  Out[31]: 2     In [30]: len(('a',)) #取元祖的元素個數,1個  Out[30]: 1  In [32]: len({'a':3,'d':4})  #len()統計字典有幾對key,value  Out[32]: 2

4、商和餘數divmod() 

In [35]: help(divmod)  divmod(...)      divmod(x, y) -> (quotient, remainder)          Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.  (END)   In [36]: divmod(5,2)    Out[36]: (2, 1)    #商和餘數

5、pow()次方&取余

In [37]: help(pow)  Help on built-in function pow in module __builtin__:  pow(...)      pow(x, y[, z]) -> number          With two arguments, equivalent to x**y.  With three arguments,      equivalent to (x**y) % z, but may be more efficient (e.g. for longs).  (END)   In [38]: pow(2,3)   #兩個參數,結果是x的y次方  Out[38]: 8    In [40]: pow(2,3,3) #三個參數,結果是x的y次方之後,2^3=8,8%3=2,再取個余結果是2,也就是取模  Out[40]: 2  In [39]: pow(2,3,4)  Out[39]: 0

6、round()

第一步把數字變為浮點數,

第二步,沒有第二參數,把一個數字四捨五入,默認保留一位小數點.0 ,有第二個參數,第二個參數是保留幾位小數

In [41]: help(round)  Help on built-in function round in module __builtin__:  round(...)      round(number[, ndigits]) -> floating point number          Round a number to a given precision in decimal digits (default 0 digits).      This always returns a floating point number.  Precision may be negative.  (END)   In [53]: print round(12.145) #默認是  12.0  In [15]: round(12.145,1)  Out[15]: 12.1  In [14]: round(12.145,2)  Out[14]: 12.14  In [54]: print round(12.145,3)   12.145  In [55]: print round(12.145,4)   12.145

7、callable()對象是否可調用的?

In [63]: help(callable)    Help on built-in function callable in module __builtin__:  callable(...)      callable(object) -> bool #返回一個bool值         Return whether the object is callable (i.e., some kind of function).      Note that classes are callable, as are instances with a __call__() method.    In [64]: a = 123  In [65]: callable(a)  #字元a不可調用  Out[65]: False    In [66]: def b():      ...:     pass      ...:   In [67]: callable(b)#函數b可調用  Out[67]: True        In [69]: class A(object):  #定義了一個對象也是可調用的,返回true      ...:     pass      ...:   In [70]: callable(A)  Out[70]: True

8、type()確定類型

In [66]: def b():      ...:     pass  In [73]: print type(b)  #b為function函數類型  <type 'function'>    In [64]: a = 123  In [74]: print type(a) #a是int×××  <type 'int'>  In [75]: print type([])  <type 'list'>

9、isinstance(a,int)判斷是不是指定類型,是的話返回True,不是的話,返回False

In [19]: isinstance(a,int)  Out[19]: True  In [25]: l = [1,32]  In [28]: if type(l) == type([]):      ...:     print 'ok'      ...:       ok  In [29]: isinstance(l,list)  Out[29]: True    In [30]: isinstance(l,tuple)  Out[30]: False    In [36]: isinstance(l,(list,tuple,str)) #l是list或者tuple或者str嗎?是的,就返回True  Out[36]: True

10、cmp()比較數字或者字元串的大小

In [55]: cmp(2,5)  Out[55]: -1    In [56]: cmp(2,2)  Out[56]: 0    In [57]: cmp(2,1)  Out[57]: 1    In [61]: cmp('hello','hello') #字元串相同,返回0  Out[61]: 0  In [63]: cmp('zello','hello')#首字母,z>h的ASCII值,所以,返回1  Out[63]: 1  In [62]: cmp('hello,world','hello')#逗號,的ASCII值大於null=0,返回1,  Out[62]: 1  In [65]: cmp('aellohello','hello')#ASCII值a<h,返回-1  Out[65]: -1

11、range和xrange()

In [75]: a=range(10) #直接分配記憶體,消耗資源    In [76]: a  Out[76]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]    In [77]: b=xrange(10)    In [78]: b  Out[78]: xrange(10)  #在循環遍歷的時候再分配資源,節約資源    In [79]: for i in b:print i  0  1  2  3  4  5  6  7  8  9

二、python類型轉換

1、int()轉換為×××,如果轉換字元串,必須全是數字,不能包括其他非數字字元

In [123]: int(0x12)  Out[123]: 18  In [1]: int('54')  Out[1]: 54      In [124]: int('0x12') #錯,字元串包含了非數字x,只能是『12』才能轉為int  12  ---------------------------------------------------------------------------  ValueError                                Traceback (most recent call last)  <ipython-input-124-d8b06269903d> in <module>()  ----> 1 int('0x12')    ValueError: invalid literal for int() with base 10: '0x12'    In [85]: int('12.479')#錯,字元串包含了非數字 '.',只能是『12479』才能轉為int 12479,  ---------------------------------------------------------------------------  ValueError                                Traceback (most recent call last)  <ipython-input-85-4191248f183f> in <module>()  ----> 1 int('12.479')    ValueError: invalid literal for int() with base 10: '12.479'

2、long()轉換為長×××,與int類似用法,轉換字元串不能包括非數字的字元

In [87]: long(12.4)  Out[87]: 12L    In [88]: long(12.5678)  Out[88]: 12L    In [89]: long('12')  Out[89]: 12L    In [90]: long('12.4')  ---------------------------------------------------------------------------  ValueError                                Traceback (most recent call last)  <ipython-input-90-5122883443e4> in <module>()  ----> 1 long('12.4')    ValueError: invalid literal for long() with base 10: '12.4'

3、hex()轉換為16進位

hex(...)      hex(number) -> string  #返回16進位的字元串,參數是int或者長×××Long int      Return the hexadecimal representation of an integer or long integer.  In [117]: hex(12)  Out[117]: '0xc'

4、float()轉換為float類型

In [98]: float('123')  Out[98]: 123.0    In [99]: float(123)  Out[99]: 123.0

5、轉換為複數類型

In [100]: complex(123)  Out[100]: (123+0j)

6、str(),轉換為string字元串類型

In [104]: str(123)  Out[104]: '123'    In [105]: str('123')  Out[105]: '123'    In [106]: str([1,2])  Out[106]: '[1, 2]'    In [107]: str({'1':1})  Out[107]: "{'1': 1}"    In [108]: str((1,[2,3]))  Out[108]: '(1, [2, 3])'

7、list()轉換為列表

class list(object)   |  list() -> new empty list #參數為空,返回空列表   |  list(iterable) -> new list initialized from iterable's items#參數是可迭代對象,返回迭代元素的新列表  In [110]: list('123')  參數是可迭代對象,返回迭代元素的新列表  Out[110]: ['1', '2', '3']    In [111]: list()#參數為空,返回空列表  Out[111]: []    In [112]: list((3,4,[56]))  Out[112]: [3, 4, [56]]    In [113]: list((3,4,[5,6]))#把元祖變為列表  Out[113]: [3, 4, [5, 6]]

8、tuple()轉換為元祖

In [114]: tuple([3, 4, [5, 6]])#把列表變為元祖  Out[114]: (3, 4, [5, 6])

9、eval()就是字元串去字元化,刪除引號,把字元串當成有效的表達式求值

In [127]: eval('0xa')  Out[127]: 10  In [2]: type(eval('0xa'))#注意轉換後類型是int  Out[2]: int  In [129]: eval("['a','b',1]")  Out[129]: ['a', 'b', 1]

10、oct()轉換為8進位

In [131]: oct(10)  Out[131]: '012'

11、chr()返回ASCII值0-255對應的字元

In [148]: chr(65)  Out[148]: 'A'

12、ord()返回字元的ASCII值

In [143]: ord('a')  Out[143]: 97    In [144]: ord('A')  Out[144]: 65

三、字元串處理函數

1、str.capitalizw()

In [159]: s='hello,world'  In [160]: help(s.capitalize)  capitalize(...)      S.capitalize() -> string #返回字元串,首字母大寫      Return a copy of the string S with only its first character      capitalized.  In [161]: s.capitalize()  Out[161]: 'Hello,world'    #H已經變為大寫

2、str.replace()

replace(...)      S.replace(old, new[, count]) -> string #用新字元串替換舊字元串,count定義替換幾次            Return a copy of string S with all occurrences of substring      old replaced by new.  If the optional argument count is      given, only the first count occurrences are replaced.        In [172]: s.replace('h','H')  #用H替換所有h  Out[172]: 'Hello,world,H'    In [169]: s.replace('h','H',1)#用H替換所有h,如果為1,只替換第一次出現的h  Out[169]: 'Hello,world,h'    In [170]: s.replace('h','H',2)#用H替換所有h,如果為2,只替換前2次出現的h  Out[170]: 'Hello,world,H'

3、str.split()

split(...)      S.split([sep [,maxsplit]]) -> list of strings            Return a list of the words in the string S, using sep as the      delimiter string.  If maxsplit is given, at most maxsplit      splits are done. If sep is not specified or is None, any      whitespace string is a separator and empty strings are removed      from the result.    In [176]: s1='abc'  In [177]: s1.split()  Out[177]: ['abc']    In [174]: s = 'hello  atbnc'  In [175]: s.split()  #默認空格、tab、enter換行都會作為分隔符切分字元串  Out[175]: ['hello', 'a', 'b', 'c']        #分別以換行n,空格' ',tab為分割符切換字元串  In [180]: s.split('n')  Out[180]: ['hello  atb', 'c']    In [181]: s.split(' ')  Out[181]: ['hello', '', 'atbnc']    In [182]: s.split('t')  Out[182]: ['hello  a', 'bnc']  In [183]: ip = '192.168.1.1'  In [185]: ip.split('.')  Out[185]: ['192', '168', '1', '1']  In [186]: ip.split('.',2)  Out[186]: ['192', '168', '1.1']    In [187]: ip.split('.',1)  Out[187]: ['192', '168.1.1']

4、str.join()

In [188]: help(str.join)  join(...)      S.join(iterable) -> string#參數是可迭代的對象,返回的是字元串            Return a string which is the concatenation of the strings in the      iterable.  The separator between elements is S.  In [189]: s1='abc'    In [190]: s1.join('12') #在1,2之間使用abc去連接  Out[190]: '1abc2'    In [191]: s1.join('123')#在1,2,3之間用abc去連接  Out[191]: '1abc2abc3'    In [194]: ''.join(str(i) for i in range(10))#把列表的每個元素通過列表重寫變為字元串  Out[194]: '0123456789'    In [195]: ' '.join(str(i) for i in range(10))  Out[195]: '0 1 2 3 4 5 6 7 8 9'  In [197]: int(''.join(str(i) for i in range(10)))  Out[197]: 123456789

5、string模組

In [198]: import string    In [199]: string.upper('abc')  Out[199]: 'ABC'    In [200]: string.lowercase  Out[200]: 'abcdefghijklmnopqrstuvwxyz'    In [201]: string.uppercase  Out[201]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'    In [202]: help(string.capitalize)      In [203]: string.capitalize('hello')  Out[203]: 'Hello'    In [204]: help(string.replace)      In [205]: string.replace('hello','o','O')  Out[205]: 'hellO'    In [206]: s  Out[206]: 'hello  atbnc'    In [207]: s.replace('h','H')  Out[207]: 'Hello  atbnc'

三、序列處理函數

1、filter()數據過濾處理函數,例子:把range(10)通過函數f處理,偶數顯示在列表中,function = None,不處理直接返回原來的列表

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  In [275]: filter(None,range(10))  #function是None,不處理直接返回range(10)  Out[275]: [1, 2, 3, 4, 5, 6, 7, 8, 9]  In [271]: def f(x):       ...:     if x %2 == 0:       ...:         return True       ...:       In [273]: filter(f,range(10)) #把range(10)通過函數f處理,偶數顯示在列表中  Out[273]: [0, 2, 4, 6, 8]    #filter使用匿名函數lambda  In [303]: filter(lambda x: x%2==0,range(10))#表示,lambda x成立的條件是:x%2==0並且x屬於range(10)  Out[303]: [0, 2, 4, 6, 8]

2、zip()對多個序列處理,合併成一個大的序列

zip(...)      zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]            Return a list of tuples, where each tuple contains the i-th element      from each of the argument sequences.  The returned list is truncated      in length to the length of the shortest argument sequence.#最小的參數  In [277]: l1 = [1,2,3]  In [278]: l2 = ['a','b','c']  In [279]: zip(l1,l2)  Out[279]: [(1, 'a'), (2, 'b'), (3, 'c')]  In [280]: dict(zip(l1,l2))  Out[280]: {1: 'a', 2: 'b', 3: 'c'}    In [284]: l3 = ['I','II']#l3的長度少一個,結果也會少一個    In [285]: zip(l1,l2,l3)  Out[285]: [(1, 'a', 'I'), (2, 'b', 'II')]

3、map()返回列表,通過函數對序列相應的元素進行處理,如果需要處理一個序列,對應函數的參數是一個,如果需要處理的是兩個序列,對應函數的桉樹是三個,以此類推。

map(...)      map(function, sequence[, sequence, ...]) -> list            Return a list of the results of applying the function to the items of      the argument sequence(s).  If more than one sequence is given, the      function is called with an argument list consisting of the corresponding      item of each sequence, substituting None for missing values when not all      sequences have the same length.  If the function is None, return a list of      the items of the sequence (or a list of tuples if more than one sequence).  In [287]: map(None,l1,l2,l3)  Out[287]: [(1, 'a', 'I'), (2, 'b', 'II'), (3, 'c', None)]    In [288]: def f(x):       ...: return x**2       ...:   In [289]: map(f,l1)  #通過函數f對l1的每個參數處理,一個序列,對應函數的一個參數  Out[289]: [1, 4, 9]    In [294]: l1  Out[294]: [1, 2, 3]  In [290]: l2=[4,5,6]  In [292]: def f(x,y):    #定義函數,返回乘積,兩個序列,對應函數的兩個參數       ...:     return x*y       ...:   In [293]: map(f,l1,l2) #給了兩個序列,則這兩個序列都會被函數f處理,並返回結果  Out[293]: [4, 10, 18]    注意:如果需要處理的是三個序列,對應函數的三個參數,以此類推。  #map使用匿名函數lambda  In [304]: map(lambda x,y: x*y,range(10),range(10))  Out[304]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

4、reduce() 返回值value, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5)

In [295]: help(reduce)  reduce(...)      reduce(function, sequence[, initial]) -> value            Apply a function of two arguments cumulatively to the items of a sequence,      from left to right, so as to reduce the sequence to a single value.      For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates      ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items      of the sequence in the calculation, and serves as a default when the      sequence is empty.

In [296]: def f(x,y):

     …:     return x+y

     …: 

In [297]: reduce(f,range(1,101))

Out[297]: 5050

#reduce使用匿名函數lambda

In [300]: reduce(lambda x,y:x+y,[1,2,3,4,5])

Out[300]: 15

5、列表表達式(列表重寫)

In [305]: [i for i in range(10)]  Out[305]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]    In [306]: [i*2 for i in range(10)]  Out[306]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]    In [307]: [i**2 for i in range(10)]  Out[307]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]      In [308]: [i for i in range(10) if i %3==0]  Out[308]: [0, 3, 6, 9]    In [309]: [i*2 for i in range(10) if i %3==0]  Out[309]: [0, 6, 12, 18]    In [310]: [i*2+10 for i in range(10) if i %3==0]  Out[310]: [10, 16, 22, 28]