天天看點

python内置函數

The Python interpreter has a number of functions built into it that are always available. They are listed here in alphabetical order.

Built-in Functions
abs() divmod() input() open() staticmethod()
all() enumerate() int() ord() str()
any() eval() isinstance() pow() sum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bool() filter() len() range() type()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset() long() reload() vars()
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reversed() zip()
compile() hasattr() memoryview() round() __import__()
complex() hash() min() set() apply()
delattr() help() next() setattr() buffer()
dict() hex() object() slice() coerce()
dir() id() oct() sorted() intern()

詳細使用參考:http://docs.python.org/2/library/functions.html

Table of Contents

1. 常用函數
2. 内置類型轉換函數
3. 序列處理函數
4. String子產品

Chapter 1. 常用函數

  • abs(x)

    abs()傳回一個數字的絕對值。如果給出複數,傳回值就是該複數的模。

    >>>print abs(-100) 100 >>>print abs(1+2j) 2.2360679775      
  • callable(object)

    callable()函數用于測試對象是否可調用,如果可以則傳回1(真);否則傳回0(假)。可調用對象包括函數、方法、代碼對象、類和已經定義了“調用”方法的類執行個體。

    >>> a="123" >>> print callable(a) 0 >>> print callable(chr) 1      
  • cmp(x,y)

    cmp()函數比較x和y兩個對象,并根據比較結果傳回一個整數,如果x<y,則傳回-1;如果x>y,則傳回1,如果x==y則傳回0。

    >>>a=1 >>>b=2 >>>c=2 >>> print cmp(a,b) -1 >>> print cmp(b,a) 1 >>> print cmp(b,c) 0      
  • divmod(x,y)

    divmod(x,y)函數完成除法運算,傳回商和餘數。

    >>> divmod(10,3) (3, 1) >>> divmod(9,3) (3, 0)      
  • isinstance(object,class-or-type-or-tuple) -> bool

    測試對象類型

    >>> a='isinstance test' >>> b=1234 >>> isinstance(a,str) True >>> isinstance(a,int) False >>> isinstance(b,str) False >>> isinstance(b,int) True      
  • len(object) -> integer

    len()函數傳回字元串和序列的長度。

    >>> len("aa") 2 >>> len([1,2]) 2      
  • pow(x,y[,z])

    pow()函數傳回以x為底,y為指數的幂。如果給出z值,該函數就計算x的y次幂值被z取模的值。

    >>> print pow(2,4) 16 >>> print pow(2,4,2) 0 >>> print pow(2.4,3) 13.824      
  • range([lower,]stop[,step])

    range()函數可按參數生成連續的有序整數清單。

    >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1,10,2) [1, 3, 5, 7, 9]      
  • round(x[,n])

    round()函數傳回浮點數x的四舍五入值,如給出n值,則代表舍入到小數點後的位數。

    >>> round(3.333) 3.0 >>> round(3) 3.0 >>> round(5.9) 6.0      
  • type(obj)

    type()函數可傳回對象的資料類型。

    >>> type(a) <type 'list'> >>> type(copy) <type 'module'> >>> type(1) <type 'int'>      
  • xrange([lower,]stop[,step])

    xrange()函數與range()類似,但xrnage()并不建立清單,而是傳回一個xrange對象,它的行為與清單相似,但是隻在需要時才計算清單值,當清單很大時,這個特性能為我們節省記憶體。

    >>> a=xrange(10) >>> print a[0] 0 >>> print a[1] 1 >>> print a[2] 2      

Chapter 2. 内置類型轉換函數

  • chr(i)

    chr()函數傳回ASCII碼對應的字元串。

    >>> print chr(65) A >>> print chr(66) B >>> print chr(65)+chr(66) AB      
  • complex(real[,imaginary])

    complex()函數可把字元串或數字轉換為複數。

    >>> complex("2+1j") (2+1j) >>> complex("2") (2+0j) >>> complex(2,1) (2+1j) >>> complex(2L,1) (2+1j)      
  • float(x)

    float()函數把一個數字或字元串轉換成浮點數。

    >>> float("12") 12.0 >>> float(12L) 12.0 >>> float(12.2) 12.199999999999999      
  • hex(x)

    hex()函數可把整數轉換成十六進制數。

    >>> hex(16) '0x10' >>> hex(123) '0x7b'      
  • long(x[,base])

    long()函數把數字和字元串轉換成長整數,base為可選的基數。

    >>> long("123") 123L >>> long(11) 11L      
  • list(x)

    list()函數可将序列對象轉換成清單。如:

    >>> list("hello world") ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] >>> list((1,2,3,4)) [1, 2, 3, 4]      
  • int(x[,base])

    int()函數把數字和字元串轉換成一個整數,base為可選的基數。

    >>> int(3.3) 3 >>> int(3L) 3 >>> int("13") 13 >>> int("14",15) 19      
  • min(x[,y,z...])

    min()函數傳回給定參數的最小值,參數可以為序列。

    >>> min(1,2,3,4) 1 >>> min((1,2,3),(2,3,4)) (1, 2, 3)      
  • max(x[,y,z...])

    max()函數傳回給定參數的最大值,參數可以為序列。

    >>> max(1,2,3,4) 4 >>> max((1,2,3),(2,3,4)) (2, 3, 4)      
  • oct(x)

    oct()函數可把給出的整數轉換成八進制數。

    >>> oct(8) '010' >>> oct(123) '0173'      
  • ord(x)

    ord()函數傳回一個字元串參數的ASCII碼或Unicode值。

    >>> ord("a") 97 >>> ord(u"a") 97      
  • str(obj)

    str()函數把對象轉換成可列印字元串。

    >>> str("4") '4' >>> str(4) '4' >>> str(3+2j) '(3+2j)'      
  • tuple(x)

    tuple()函數把序列對象轉換成tuple。

    >>> tuple("hello world") ('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd') >>> tuple([1,2,3,4]) (1, 2, 3, 4)      

Chapter 3. 序列處理函數

  • 常用函數中的len()、max()和min()同樣可用于序列。
  • filter(function,list)

    調用filter()時,它會把一個函數應用于序列中的每個項,并傳回該函數傳回真值時的所有項,進而過濾掉傳回假值的所有項。

    >>> def nobad(s): ... return s.find("bad") == -1 ... >>> s = ["bad","good","bade","we"] >>> filter(nobad,s) ['good', 'we']      
    這個例子通過把nobad()函數應用于s序列中所有項,過濾掉所有包含“bad”的項。
  • map(function,list[,list])

    map()函數把一個函數應用于序列中所有項,并傳回一個清單。

    >>> import string >>> s=["python","zope","linux"] >>> map(string.capitalize,s) ['Python', 'Zope', 'Linux']      
    map()還可同時應用于多個清單。如:
    >>> import operator >>> s=[1,2,3]; t=[3,2,1] >>> map(operator.mul,s,t) # s[i]*t[j] [3, 4, 3]      
    如果傳遞一個None值,而不是一個函數,則map()會把每個序列中的相應元素合并起來,并傳回該元組。如:
    >>> a=[1,2];b=[3,4];c=[5,6] >>> map(None,a,b,c) [(1, 3, 5), (2, 4, 6)]      
  • reduce(function,seq[,init])

    reduce()函數獲得序列中前兩個項,并把它傳遞給提供的函數,獲得結果後再取序列中的下一項,連同結果再傳遞給函數,以此類推,直到處理完所有項為止。

    >>> import operator >>> reduce(operator.mul,[2,3,4,5]) # ((2*3)*4)*5 120 >>> reduce(operator.mul,[2,3,4,5],1) # (((1*2)*3)*4)*5 120 >>> reduce(operator.mul,[2,3,4,5],2) # (((2*2)*3)*4)*5 240      
  • zip(seq[,seq,...])

    zip()函數可把兩個或多個序列中的相應項合并在一起,并以元組的格式傳回它們,在處理完最短序列中的所有項後就停止。

    >>> zip([1,2,3],[4,5],[7,8,9]) [(1, 4, 7), (2, 5, 8)]      
    如果參數是一個序列,則zip()會以一進制組的格式傳回每個項,如:
    >>> zip((1,2,3,4,5)) [(1,), (2,), (3,), (4,), (5,)] >>> zip([1,2,3,4,5]) [(1,), (2,), (3,), (4,), (5,)]      

zip([iterable, ...])

This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

zip() in conjunction with the * operator can be used to unzip a list:(python沒有unzip函數,但是将zip和*結合起來相當于unzip函數)

>>>

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped) //[(1, 2, 3), (4, 5, 6)]
>>> x == list(x2) and y == list(y2)
True
      

 二維數組得到每行之和:

  1. >>> list = [[0,1,2],[3,1,4]]  
  2. >>> [sum(x) for x in list]  
  3. [3, 8]  
  4. >>> map(sum,list)  
  5. [3, 8]  

二維數組要得到每列之和怎麼辦?

如果要得到每列之和,需要用zip(*list)先unzip list,得到一個元組list,其中第i個元組包含了每行的第i個元素:

  1. >>> zip(*list)  
  2. [(0, 3), (1, 1), (2, 4)]  
  3. >>> [sum(x) for x in zip(*list)]  
  4. [3, 2, 6]  
  5. >>> map(sum,zip(*list))  
  6. [3, 2, 6]  

下面的例子是關于zip和unzip(其實是zip和*一起用)如何work的:

  1. >>> x=[1,2,3]  
  2. >>> y=[4,5,6]  
  3. >>> zipped = zip(x,y)  
  4. >>> zipped  
  5. [(1, 4), (2, 5), (3, 6)]  
  6. >>> x2,y2=zip(*zipped)  
  7. >>> x2  
  8. (1, 2, 3)  
  9. >>> y2  
  10. (4, 5, 6)  
  11. >>> x3,y3=map(list,zip(*zipped))  
  12. >>> x3  
  13. [1, 2, 3]  
  14. >>> y3  
  15. [4, 5, 6]  

*星号用法:

Unpacking Argument Lists

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]
      

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !      

Chapter 4. String子產品

  • replace(string,old,new[,maxsplit])

    字元串的替換函數,把字元串中的old替換成new。預設是把string中所有的old值替換成new值,如果給出maxsplit值,還可控制替換的個數,如果maxsplit為1,則隻替換第一個old值。

    >>>a="11223344" >>>print string.replace(a,"1","one") oneone2223344 >>>print string.replace(a,"1","one",1) one12223344      
  • capitalize(string)
    >>> import string >>> print string.capitalize("python") Python      
  • >>> import string >>> ip="192.168.3.3" >>> ip_list=string.split(ip,'.') >>> print ip_list ['192', '168', '3', '3']