zoukankan      html  css  js  c++  java
  • 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

    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 lengthzip() 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. [38]  
    4. >>> map(sum,list)  
    5. [38]  

    二维数组要得到每列之和怎么办?

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

    1. >>> list = [[0,1,2],[3,1,4]]  
    2. >>> zip(*list)  
    3. [(03), (11), (24)]  
    4. >>> [sum(x) for x in zip(*list)]  
    5. [326]  
    6. >>> map(sum,zip(*list))  
    7. [326]  

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

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

    *星号用法:

    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
    • split(string,sep=None,maxsplit=-1)

      从string字符串中返回一个列表,以sep的值为分界符。

      >>> import string >>> ip="192.168.3.3" >>> ip_list=string.split(ip,'.') >>> print ip_list ['192', '168', '3', '3']
  • 相关阅读:
    透明的LISTVIEW
    循序渐进实现仿QQ界面(三):界面调色与控件自绘
    循序渐进实现仿QQ界面(一):园角矩形与双缓冲贴图窗口
    循序渐进实现仿QQ界面(二):贴图按钮的三态模拟
    C#中如何通过点击按钮切换窗口
    jQuery -- 光阴似箭(二):jQuery效果的使用
    jQuery -- 光阴似箭(一):初见 jQuery -- 基本用法,语法,选择器
    JavaScript -- 时光流逝(十三):DOM -- Console 对象
    JavaScript -- 时光流逝(十二):DOM -- Element 对象
    JavaScript -- 时光流逝(十一):DOM -- Document 对象
  • 原文地址:https://www.cnblogs.com/youxin/p/3059990.html
Copyright © 2011-2022 走看看