zoukankan      html  css  js  c++  java
  • Python学习进程(15)常用内置函数

        本节介绍Python的一些常用的内置函数。

        (1)cmp(x, y):

        cmp()函数比较 x 和 y 两个对象,并根据比较结果返回一个整数,如果 x<y,则返回-1;如果x>y,则返回 1,如果 x==y 则返回 0。

    >>> cmp(str1,str2)
    -1
    >>> num1=10;num2=20;
    >>> cmp(num1,num2)
    -1
    >>> list1=["abc","MenAngel",True]
    >>> list2=["abc","MenAngel",False]
    >>> cmp(list1,list2)
    1

        在Python2.7x版本中cmp比较函数不够严谨,他可以进行除复数外任意类型的比较,但在Python3.5x版本中仅限同一类型的比较。

        (2)len(object) -> integer:

        len()函数返回字符串或者序列的长度。

    >>> str="人生何不潇洒走一回"
    >>> len(str)
    18
    >>> list_test=["山川","驻美","美貌",True,80]
    >>> len(list_test)
    5
    >>> tuple_test=("Hello","World",8j,False,5/4)
    >>> len(tuple_test)
    5

        (3)range([lower,]stop[,step]):

        range()函数可按参数生成连续的有序整数列表。

    >>> num_list1=range(10)
    >>> print num_list1
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> num_list2=range(5,10)
    >>> print num_list2
    [5, 6, 7, 8, 9]
    >>> num_list3=range(5,15,3)
    >>> print num_list3
    [5, 8, 11, 14]
    >>> num_list4=range(20,10,-2)
    >>> print num_list4
    [20, 18, 16, 14, 12]

        (4)xrange([lower,]stop[,step]):    

        xrange()函数与 range()类似,但 xrnage()并不创建列表,而是返回一个 xrange 对象,它的行为与列表相似,但是只在需要时才计算列表值,当列表很大时,这个特性能为我们节省内存。

    >>> xrange(10)
    xrange(10)
    >>> xrange(11,22,2)
    xrange(11, 23, 2)
    >>> list(xrange(10))
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> list(xrange(11,22,2))
    [11, 13, 15, 17, 19, 21]

        (5)float(x):

        float()函数把一个数字或字符串转换成浮点数。

    >>> float("123.4")
    123.4
    >>> float("5")
    5.0
    >>> float(5)
    5.0

        (6)hex(x):

        hex()函数可把整数转换成十六进制数。

    >>> hex(50)
    '0x32'
    >>> hex(32)
    '0x20'

        (7)list(x)或tuple(x):

        list()函数可将序列对象转换成列表。tuple()函数可将列表转化为序列。

    >>> list('MenAngel')
    ['M', 'e', 'n', 'A', 'n', 'g', 'e', 'l']
    >>> list(("Men","Women",True,80))
    ['Men', 'Women', True, 80]
    >>> tuple(xrange(10,20,2))
    (10, 12, 14, 16, 18)
    >>> tuple(list(xrange(20,10,-5)))
    (20, 15)

        (8)int(x[,base]):

        int()函数把数字和字符串转换成一个整数,base 为可选的基数。

    >>> int(123.4)
    123
    >>> int("123")
    123

        (9)min(x[,y,z...])或max(x[,y,z...]):

        min()函数返回给定参数的最小值,参数可以为序列。max函数返回最大值。

    >>> tuple_test1=(1,2,3,4,5)
    >>> list_test1=[1,2,3,4,5]
    >>> tuple_test2=(2,3,4,5,6)
    >>> min(tuple_test1);max(list_test1)
    1
    5
    >>> min(tuple_test1,tuple_test2)
    (1, 2, 3, 4, 5)

        (10)zip(seq[,seq,...]):

        zip()函数可把两个或多个序列中的相应项合并在一起,并以元组的格式返回它们,在处理完最短序列中的所有项后就停止。

    >>> list1=[1,2,3]
    >>> list2=[4,5,6]
    >>> list3=[7,8,9]
    >>> zip(list1,list2,list3)
    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    >>> list4=[10,11,12,13]
    >>> zip(list1,list4)
    [(1, 10), (2, 11), (3, 12)]
    >>> zip(list4)
    [(10,), (11,), (12,), (13,)]
    >>> zip()
    []
    >>> zip(*zip(list1,list2,list3))
    [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
    >>> x = [1, 2, 3]
    >>> zip(* [x] * 3)
    [(1, 1, 1), (2, 2, 2), (3, 3, 3)]
    >>> [x]*3
    [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

        (11)replace(string,old,new[,maxsplit]):

        字符串的替换函数,把字符串中的 old 替换成 new。默认是把 string 中所有的 old 值替换成 new值,如果给出 maxsplit 值,还可控制替换的个数,如果 maxsplit 为 1,则只替换第一个 old 值。

    >>> str
    'MenAnge123sunjimeng,sunjimeng123MenAngel,He123My friend'
    >>> str.replace('123','is')
    'MenAngeissunjimeng,sunjimengisMenAngel,HeisMy friend'
    >>> str.replace('123','is',2)
    'MenAngeissunjimeng,sunjimengisMenAngel,He123My friend'
    >>> str.replace('123','is',3)
    'MenAngeissunjimeng,sunjimengisMenAngel,HeisMy friend'

        (12)split(string,sep=None,maxsplit=-1):

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

    >>> str="www.blog.com/MenAngel/Index"
    >>> str.split('.')
    ['www', 'blog', 'com/MenAngel/Index']
    >>> str.split('/')
    ['www.blog.com', 'MenAngel', 'Index']
    >>> str.split('/',1)
    ['www.blog.com', 'MenAngel/Index']
    >>> string="win10&&win9&&win7"
    >>> string.split('&&')
    ['win10', 'win9', 'win7']

        (13)abs(x):

        abs()返回一个数字的绝对值。如果给出复数,返回值就是该复数的模。

    >>> abs(-10)
    10
    >>> abs(-3j+4)
    5.0

        (14)callable(object):

        callable()函数用于测试对象是否可调用,如果可以则返回1(真);否则返回0(假)。可调用对象包括函数、方法、代码对象、类和已经定义了“调用”方法的类实例。

    >>> callable(str)
    True
    >>> def sum(var1,var2):
    ...   return var1+var2
    ... 
    
    >>> callable(sum)
    True
    >>> name="MenAngel"
    >>> callable(name)
    False
    >>> callable(xrange(10))
    False
    >>> callable(range(10))
    False

        (15)divmod(x,y):

        divmod(x,y)函数完成除法运算,返回商和余数。

    >>> divmod(10,3)
    (3, 1)
    >>> divmod(4+8j,2)
    ((2+0j), 8j)

        (16)isinstance(object,class-or-type-or-tuple) -> bool:

        测试对象类型

    >>> name="MenAngel"
    >>> isinstance(name,str)
    True
    >>> num=100
    >>> isinstance(num,int)
    True
    >>> isinstance(num,float)
    False
    >>> isinstance(True,bool)
    True

        (17)pow(x,y[,z]):

        pow()函数返回以x为底,y为指数的幂。如果给出z值,该函数就计算x的y次幂值被z取模的值。

    >>> pow(2,3)
    8
    >>> pow(4,4,5)
    1
    >>>

        (18)round(x[,n]):

        round()函数返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。

    >>> round(12.345)
    12.0
    >>> round(12.345678,2)
    12.35

        (19)type(obj):

        type()函数可返回对象的数据类型。

    >>> type("MenAngel")
    <type 'str'>
    >>> type(True)
    <type 'bool'>
    >>> type(40)
    <type 'int'>
    >>> type(6/4)
    <type 'int'>
    >>> type(12.5)
    <type 'float'>
    >>> type(6.0/4)
    <type 'float'>
    >>> type(9j)
    <type 'complex'>
    >>> type(["sg","sb",True])
    <type 'list'>
    >>> type(("a",True))
    <type 'tuple'>
    >>> type({"a":"MenAngel","1":"67"})
    <type 'dict'>

        (20)chr(i):

        chr()函数返回ASCII码对应的字符串。

    >>> chr(53)
    '5'
    >>> chr(56)
    '8'
    >>> chr(106)
    'j'

        (21)oct(x):

        oct()函数可把给出的整数转换成八进制数。

    >>> oct(10)
    '012'
    >>> oct(64)
    '0100'

        (22)ord(x):

        ord()函数返回一个字符串参数的ASCII码或Unicode值。

    >>> ord('z')-ord('a')
    25
    >>> ord(u'?')
    63
    >>> ord(u'9')
    57

        (23)filter(function,list):

        调用filter()时,它会把一个函数应用于序列中的每个项,并返回该函数返回真值时的所有项,从而过滤掉返回假值的所有项。

    >>> def noMen(str):
    ...   return str.find("Men")==-1
    ...
    >>> s=["I am Men","I am WoMen","Hello","World"]
    >>> filter(noMen,s)
    ['Hello', 'World']

        (24)map(function,list[,list]):

        map()函数把一个函数应用于序列中所有项,并返回一个列表。

    >>> import string
    >>> s="www.hello.com"
    >>> map(string.capitalize,s.split('.'))
    ['Www', 'Hello', 'Com']
    >>> import operator
    >>> s=[1,2,3];t=[4,5,6];           #同时应用于多个列表
    >>> map(operator.mul,s,t)
    [4, 10, 18]
    >>> a=[1,2];b=[3,4];c=[5,6];
    >>> map(None,a,b,c)                #如果传递一个None值,而不是一个函数,则map()会把每个序列中的相应元素合并起来,并返回该元组。
    [(1, 3, 5), (2, 4, 6)] 
    >>> zip(a,b,c)
    [(1, 3, 5), (2, 4, 6)]

        (25)reduce(function,seq[,init]):

        reduce()函数获得序列中前两个项,并把它传递给提供的函数,获得结果后再取序列中的下一项,连同结果再传递给函数,以此类推,直到处理完所有项为止。

    >>> import operator
    >>> a=[1,2,3,4];b=[5,6,7,8];
    >>> map(operator.add,a,b)
    [6, 8, 10, 12]
    >>> reduce(operator.add,a)
    10
  • 相关阅读:
    【项目】项目1
    Python脚本1
    Python基础24
    Python基础23(习惯)
    01-Spring(1)
    12-Shell(2)
    11-Shell(1)
    10-搭建EE环境
    09-常用指令(3)
    08-常用指令(2)
  • 原文地址:https://www.cnblogs.com/MenAngel/p/5716569.html
Copyright © 2011-2022 走看看