Python学习笔记之常用的内置函数

来源:互联网 发布:天津广播电视网络招聘 编辑:程序博客网 时间:2024/05/29 08:55

在Python中,python给我们提供了很多已经定义好的函数,这里列出常用的内置函数,以供参考


1.数学函数

  1. abs() 求数值的绝对值
  2. min()列表的最下值
  3. max()列表的最大值
  4. divmod() 取膜
  5. pow() 乘方
  6. round()浮点数
    #abs 绝对值函数 输出结果是1    print abs(-1)    #min 求列表最小值    #随机一个1-20的步长为2的列表    lists=range(1,20,2)    #求出列表的最小值为1    print min(lists)    #max 求列表的最大值  结果为19    print max(lists)    #divmod(x,y)  参数:2个 返回值:元祖    #函数计算公式为  ((x-x%y)/y, x%y)    print divmod(2,4)    #pow(x,y,z)    #参数:2个或者3个 z可以为空    # 计算规则 (x**y) % z    print pow(2,3,2)    #round(x)    #将传入的整数变称浮点    print round(2)

2.功能函数

  1. 函数是否可调用:callable(funcname)
  2. 类型判断:isinstance(x,list/int)
  3. 比较:cmp(‘hello’,’hello’)
  4. 快速生成序列:(x)range([start,] stop[, step])
  5. 类型判断 type()
#callable()判断函数是否可用 返回True ,这里的函数必须是定义过的def getname():    print "name"print callable(getname)#isinstance(object, classinfo)#  判断实例是否是这个类或者object是变量a=[1,3,4]print isinstance(a,int)#range([start,] stop[, step])快速生成列表# 参数一和参数三可选 分别代表开始数字和布长#返回一个2-10 布长为2的列表print range(2,10,2)#type(object) 类型判断print type(lists)

3.类型转换函数

#int(x)转换为int类型print int(2.0)#返回结果<type 'int'>print type(int(2.0))#long(x) 转换称长整形print long(10.0)#float(x) 转称浮点型print float(2)#str(x)转换称字符串print str()#list(x)转称listprint list("123")#tuple(x)转成元祖print tuple("123")#hex(x) print hex(10)#oct(x)print oct(10)#chr(x)print chr(65)#ord(x)print ord('A')

4.字符串处理

    name="zhang,wang"    #capitalize首字母大写     #Zhang,wang    print name.capitalize()    #replace 字符串替换    #li,wang    print name.replace("zhang","li")    #split 字符串分割 参数:分割规则,返回结果:列表    #['zhang', 'wang']    print name.split(",")

5.序列处理函数

strvalue="123456"a=[1,2,3]b=[4,5,6]#len 返回序列的元素的长度6print len(strvalue)#min 返回序列的元素的最小值1print min(strvalue)#max 返回序列元素的最大值6print max(strvalue)#filter 根据特定规则,对序列进行过滤#参数一:函数 参数二:序列#[2]def filternum(x):    if x%2==0:        return Trueprint filter(filternum,a)#map 根据特定规则,对序列每个元素进行操作并返回列表#[3, 4, 5]def maps(x):    return x+2print map(maps,a)#reduce  根据特定规则,对列表进行特定操作,并返回一个数值#6def reduces(x,y):    return x+yprint reduce(reduces,a)#zip  并行遍历#注意这里是根据最序列长度最小的生成#[('zhang', 12), ('wang', 33)]name=["zhang","wang"]age=[12,33,45]print zip(name,age)#序列排序sorted 注意:返回新的数列并不修改之前的序列print sorted(a,reverse=True)
原创粉丝点击