内置函数

截止到 python 版本 3.6.2,现在 python 一共为我们提供了68 个内置函数。

内置函数
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
delattr() hash() memoryview() set()

作用域相关

  • locals :函数会以字典的类型返回当前位置的全部局部变量。
  • globals:函数以字典的类型返回全部全局变量。
    1. a = 1
    2. b = 2
    3. print(locals())
    4. print(globals())
    5. # 这两个一样,因为是在全局执行的
    6. def func(argv):
    7. c = 2
    8. print(locals())
    9. print(globals())
    10. func(3)

    其他相关

字符串类型代码的执行 eval,exec,complie

  • eval:执行字符串类型的代码,并返回最终结果。
    1. ret = eval('2 + 2')
    2. print(ret)
    3. n = 20
    4. ret = eval('n + 23')
    5. print(ret)
    6. eval('print("Hello world")')
    c: 执行字符串类型的代码。
    1. s = '''
    2. for i in range(5):
    3. print(i)
    4. '''
    5. exec(s)

compile: 将字符串类型的代码编译。代码对象能够通过 exec 语句来执行或者 eval() 进行求值。

  1. 参数 source:字符串。即需要动态执行的代码段。  
  2. 参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了 source 参数时,filename 参数传入空字符即可。  
  3. 参数 model:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当 source 中包含流程语句时,model 应指定为‘exec’;当 source 中只包含一个简单的求值表达式,model 应指定为‘eval’;当 source 中包含了交互式命令语句,model 应指定为 ‘single’。
    1. # 流程语句使用exec
    2. code1 = 'for i in range(5): print(i)'
    3. compile1 = compile(code1,'','exec')
    4. exec(compile1)
    5. # 简单求值表达式用eval
    6. code2 = '1 + 2 + 3'
    7. compile2 = compile(code2,'','eval')
    8. eval(compile2)
    9. # 交互语句用single
    10. code3 = 'name = input("please input you name: ")'
    11. compile3 = compile(code3,'','single')
    12. exec(compile3)
    13. print(name)

有返回值的字符串形式的代码用 eval,没有返回值的字符串形式的代码用 exec,一般不用 compile。

输入输出相关 input,print

  • input: 函数接受一个标准输入数据,返回为 string 类型。
  • print: 打印输出。
    1. ''' 源码分析
    2. def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
    3. """
    4. print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    5. file: 默认是输出到屏幕,如果设置为文件句柄,输出到文件
    6. sep: 打印多个值之间的分隔符,默认为空格
    7. end: 每一次打印的结尾,默认为换行符
    8. flush: 立即把内容输出到流文件,不作缓存
    9. """
    10. '''
    11. print(11,22,33,sep='*')
    12. print(11,22,33,end='')
    13. print(44,55)
    14. with open('log','w',encoding='utf-8') as f:
    15. print('写入文件',file=f,flush=True)

内存相关 hash id

  • hash:获取一个对象(可哈希对象:int,str,Bool,tuple)的哈希值。

    1. print(hash(12322))
    2. print(hash('123'))
    3. print(hash('arg'))
    4. print(hash('aaron'))
    5. print(hash(True))
    6. print(hash(False))
    7. print(hash((1,2,3)))

    Python

  • id: 用于获取对象的内存地址。

    1. print(id('abc'))
    2. print(id('123'))

    Python

文件操作相关

  • open:函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。

模块相关__import__

  • __import__:函数用于动态加载类和函数 。

帮助

  • help:函数用于查看函数或模块用途的详细说明。
    1. print(help(print))
    Python

调用相关

  • callable:函数用于检查一个对象是否是可调用的。如果返回 True,object 仍然可能调用失败;但如果返回 - False,调用对象 ojbect 绝对不会成功。
    1. print(callable(0))
    2. print(callable('hello'))
    3. def demo1(a, b):
    4. return a + b
    5. print(callable(demo1))
    6. class Demo2:
    7. def test1(self):
    8. return 0
    9. print(callable(Demo2))
    10. a = Demo2()
    11. print(callable(a))
    12. # 没有实现 __call__, 返回 False
    Python

查看内置属性

  • dir:函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

    1. print(dir()) # 获得当前模块的属性列表
    2. print(dir([ ])) # 查看列表的方法

    Python

    迭代器生成器相关

  • range:函数可创建一个整数对象,一般用在 for 循环中。

  • next:内部实际使用了__next__方法,返回迭代器的下一个项目。

    1. # 首先获得Iterator对象:
    2. it = iter([1,2,3,4,5,6])
    3. # 循环
    4. while True:
    5. try:
    6. # 获得下一个值
    7. x = next(it)
    8. print(x)
    9. except StopIteration: # 遇到StopIteration就退出循环
    10. break

    Python

  • iter:函数用来生成迭代器(将一个可迭代对象,生成迭代器)。

    1. from collections import Iterable
    2. from collections import Iterator
    3. l = [1,2,3,4] # 可迭代对象,但不是迭代器
    4. print(isinstance(l,Iterable))
    5. print(isinstance(l,Iterator))
    6. l1 = iter(l) # 从一个可迭代对象生成迭代器
    7. print(isinstance(l1,Iterable))
    8. print(isinstance(l1,Iterator))

基础数据类型相关

数字相关(14 个)

数据类型(4 个):

  • bool :用于将给定参数转换为布尔类型,如果没有参数,返回 False。
  • int:函数用于将一个字符串或数字转换为整型。

    1. print(int())
    2. print(int('12'))
    3. print(int(3.6))
    4. print(int('0100',base=2)) # 将2进制的 0100 转化成十进制。结果为 4

    Python
    Copy

  • float:函数用于将整数和字符串转换成浮点数。

  • complex:函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。。

    1. print(complex(1,2))
    2. print(complex(1))
    3. print(complex("1"))
    4. print(complex("1+2j"))

    Python
    Copy
    进制转换(3 个):

  • bin:将十进制转换成二进制并返回。

  • oct:将十进制转化成八进制字符串并返回。
  • hex:将十进制转化成十六进制字符串并返回。

    1. print(bin(10),type(bin(10)))
    2. print(oct(10),type(oct(10)))
    3. print(hex(10),type(hex(10)))

    Python
    Copy
    数学运算(7):

  • abs:函数返回数字的绝对值。

  • divmod:计算除数与被除数的结果,返回一个包含商和余数的元组 (a // b, a % b)。
  • round:保留浮点数的小数位数,默认保留整数。
    -pow:函数是计算 x 的 y 次方,如果 z 在存在,则再对结果进行取模,其结果等效于 pow(x,y) %z)

    1. print(abs(-5)) # 5
    2. print(divmod(7,2)) # (3, 1)
    3. print(round(7/3,2)) # 2.33
    4. print(round(7/3)) # 2
    5. print(round(3.32567,3)) # 3.326
    6. print(pow(2,3)) # 8
    7. print(pow(2,3,3)) # 2

    Python
    Copy

  • sum:对可迭代对象进行求和计算(可设置初始值)。

  • min:返回可迭代对象的最小值(可加 key,key 为函数名,通过函数的规则,返回最小值)。
  • max:返回可迭代对象的最大值(可加 key,key 为函数名,通过函数的规则,返回最大值)。
    1. print(sum([1,2,3]))
    2. print(sum([1,2,3],100))
    3. print(min([1,2,3]))
    4. ret = min([1,2,3,-10],key=abs)
    5. print(ret)
    6. dic = {'a':3,'b':2,'c':1}
    7. print(min(dic,key=lambda x:dic[x]))
    8. # x为dic的key,lambda的返回值(即dic的值进行比较)返回最小的值对应的键
    9. print(max([1,2,3]))
    10. ret = max([1,2,3,-10],key=abs)
    11. print(ret)
    12. dic = {'a':3,'b':2,'c':1}
    13. print(max(dic,key=lambda x:dic[x]))
    Python
    Copy

数据结构相关(24 个)

列表和元祖(2 个)

  • list:将一个可迭代对象转化成列表(如果是字典,默认将 key 作为列表的元素)。
  • tuple:将一个可迭代对象转化成元祖(如果是字典,默认将 key 作为元祖的元素)。

    1. l = list((1,2,3))
    2. print(l)
    3. l = list({1,2,3})
    4. print(l)
    5. l = list({'k1':1,'k2':2})
    6. print(l)
    7. tu = tuple((1,2,3))
    8. print(tu)
    9. tu = tuple([1,2,3])
    10. print(tu)
    11. tu = tuple({'k1':1,'k2':2})
    12. print(tu)

    Python
    Copy
    相关内置函数(2 个)

  • reversed:将一个序列翻转,并返回此翻转序列的迭代器。

  • slice:构造一个切片对象,用于列表的切片。

    1. ite = reversed(['a',2,4,'f',12,6])
    2. for i in ite:
    3. print(i)
    4. l = ['a','b','c','d','e','f','g']
    5. sli = slice(3)
    6. print(l[sli])
    7. sli = slice(0,7,2)
    8. print(l[sli])

    Python
    Copy
    字符串相关(9)

  • str:将数据转化成字符串。

  • format: 与具体数据相关,用于计算各种小数,精算等。

    1. # 字符串可以提供的参数,指定对齐方式,<是左对齐, >是右对齐,^是居中对齐
    2. print(format('test','<20'))
    3. print(format('test','>20'))
    4. print(format('test','^20'))
    5. # 整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
    6. print(format(192,'b')) # 转换为二进制
    7. print(format(97,'c')) # 转换unicode成字符
    8. print(format(11,'d')) # 转换成10进制
    9. print(format(11,'o')) # 转换为8进制
    10. print(format(11,'x')) # 转换为16进制,小写字母表示
    11. print(format(11,'X')) # 转换为16进制,大写字母表示
    12. print(format(11,'n')) # 和d一样
    13. print(format(11)) # 和d一样
    14. # 浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
    15. print(format(314159265,'e')) # 科学计数法,默认保留6位小数
    16. print(format(314159265,'0.2e')) # 科学计数法,保留2位小数
    17. print(format(314159265,'0.2E')) # 科学计数法,保留2位小数,大写E
    18. print(format(3.14159265,'f')) # 小数点计数法,默认保留6位小数
    19. print(format(3.14159265,'0.10f')) # 小数点计数法,保留10位小数
    20. print(format(3.14e+10000,'F')) # 小数点计数法,无穷大转换成大小字母
    21. # g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
    22. print(format(0.00003141566,'.1g'))
    23. # p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
    24. print(format(0.00003141566,'.2g'))
    25. # p=2,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
    26. print(format(3.1415926777,'.1g'))
    27. # p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
    28. print(format(3.1415926777,'.2g'))
    29. # p=2,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
    30. print(format(3141.5926777,'.2g'))
    31. # p=2,exp=3 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
    32. print(format(0.00003141566,'.1n')) # 和g相同
    33. print(format(0.00003141566)) # 和g相同

    Python
    Copy

  • bytes:用于不同编码之间的转化。

    1. s = '你好'
    2. bs = s.encode('utf-8')
    3. print(bs)
    4. s1 = bs.decode('utf-8')
    5. print(s1)
    6. bs = bytes(s,encoding='utf-8')
    7. print(bs)
    8. b = '你好'.encode('gbk')
    9. b1 = b.decode('gbk')
    10. print(b1.encode('utf-8'))

    Python
    Copy

  • bytearry:返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。

    1. ret = bytearray('aaron',encoding='utf-8')
    2. print(id(ret))
    3. print(ret)
    4. print(ret[0])
    5. ret[0] = 65
    6. print(ret)
    7. print(id(ret))

    Python
    Copy

  • memoryview: 内存查看对象,是指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许 Python 代码访问。

    1. ret = memoryview(bytes('你好',encoding='utf-8'))
    2. print(len(ret))
    3. print(ret)
    4. print(bytes(ret[:3]).decode('utf-8'))
    5. print(bytes(ret[3:]).decode('utf-8'))

    Python
    Copy

  • ord: 输入字符找该字符编码的位置

  • chr: 输入位置数字找出其对应的字符
  • ascii: 是 ascii 码中的返回该值,不是就返回 /u…

    1. # ord 输入字符找该字符编码的位置
    2. print(ord('a'))
    3. print(ord('中'))
    4. # chr 输入位置数字找出其对应的字符
    5. print(chr(97))
    6. print(chr(20013))
    7. # 是ascii码中的返回该值,不是就返回/u...
    8. print(ascii('a'))
    9. print(ascii('中'))

    Python
    Copy

  • repr: 返回一个对象的 string 形式

    1. name = 'aaron'
    2. print('Hello %r'%name)
    3. str1 = '{"name":"aaron"}'
    4. print(repr(str1))
    5. print(str1)

    Python
    Copy
    数据集合(3 个)

  • dict:创建一个字典。

  • set:创建一个集合。
  • frozenset:返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。

相关内置函数(8 个)

  • len: 返回一个对象中元素的个数。
  • sorted:对所有可迭代的对象进行排序操作。

    1. l = [('a',1),('c',3),('d',4),('b',2)]
    2. print(sorted(l,key=lambda x:x[1]))
    3. print(sorted(l,key=lambda x:x[1],reverse=True)) # 降序

    Python
    Copy

  • enumerate: 用于将一个可遍历的数据对象 (如列表、元组或字符串) 组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

    1. print(enumerate([1,2,3]))
    2. for i in enumerate([1,2,3]):
    3. print(i)
    4. for i in enumerate([1,2,3],100):
    5. print(i)

    Python
    Copy

  • all:可迭代对象中,全都是 True 才是 True

  • any:可迭代对象中,有一个 True 就是 True

    1. print(all([1,2,True,0]))
    2. print(any([1,'',0]))

    Python
    Copy

  • zip:函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。

    1. l1 = [1,2,3,]
    2. l2 = ['a','b','c',5]
    3. l3 = ('*','**',(1,2,3))
    4. for i in zip(l1,l2,l3):
    5. print(i)

    Python
    Copy
    filter:用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

    1. def func(x): return x%2 == 0
    2. ret = filter(func,[1,2,3,4,5,6,7,8,9,10])
    3. print(ret)
    4. for i in ret:
    5. print(i)

    Python
    Copy

  • map: 会根据提供的函数对指定序列做映射。Python 3.x 返回迭代器

    1. def square(x):
    2. return x**2
    3. ret1 = map(square,[1,2,3,4,5,6,7,8])
    4. ret2 = map(lambda x:x ** 2,[1,2,3,4,5,6,7,8])
    5. ret3 = map(lambda x,y : x+y,[1,2,3,4,5,6,7,8],[8,7,6,5,4,3,2,1])
    6. for i in ret1:
    7. print(i,end=' ')
    8. print('')
    9. for i in ret2:
    10. print(i,end=' ')
    11. print('')
    12. for i in ret3:
    13. print(i,end=' ')

    Python
    Copy

匿名函数

匿名函数:为了解决那些功能很简单的需求而设计的一句话函数。

  1. # 这段代码
  2. def calc(n):
  3. return n ** n
  4. print(calc(10))
  5. # 换成匿名函数
  6. calc = lambda n: n ** n
  7. print(calc(10))

Python
Copy

匿名函数格式的说明

函数名 = lambda 参数 :返回值

  1. 参数可以有多个,用逗号隔开
  2. 匿名函数不管逻辑多复杂,只能写一行,且逻辑执行结束后的内容就是返回值
  3. 返回值和正常的函数一样可以是任意数据类型
    1. l=[3,2,100,999,213,1111,31121,333]
    2. print(max(l))
    3. dic={'k1':10,'k2':100,'k3':30}
    4. print(max(dic))
    5. print(dic[max(dic,key=lambda k:dic[k])])
    6. res = map(lambda x:x**2,[1,5,7,4,8])
    7. for i in res:
    8. print(i)
    9. res = filter(lambda x:x>10,[5,8,11,9,15])
    10. for i in res:
    11. print(i)