python-内置函数
[TOC]
python 总共有68个内置函数
数学运算(7)
| 函数 | 作用 | |
|---|---|---|
| 1 | abs(iterable) | 求数值的绝对值 |
| 2 | divmod(a, b) | 返回两个数值的商和余数 |
| 3 | max() | 返回可迭代对象或序列的元素中的最大值 |
| 4 | min() | 返回可迭代对象或序列的元素中的最小值 |
| 5 | pow(base, exp[, mod]) | 返回两个数值的幂运算或者其与指定mod的模值 |
| 6 | round() | 对浮点数进行四舍五入值 |
| 7 | sum() | 对元素类型是数值的可迭代对象中的每个元素求和 |
# abs
print(abs(-2))
2
# ------------------------------------------------------------
# divmod
print(divmod(5,2))
(2,1)
print(divmod(5.5,2))
(2.0,1.5)
# ------------------------------------------------------------
# max min
print(max('1234'))
# 传入1个可迭代对象,取其最大元素值
'4'
print(max(-1,0,key = abs))
#绝对值最大
-1
# ------------------------------------------------------------
# pow()
print(pow(2,3))
8
print( pow(2,3,5))
# pow(2,3)%5
3
# ------------------------------------------------------------
# round
print( round(1.1314926,1))
1.1
print( round(1.1314926,5))
1.13149
print(sum(range(5)))
#15
类型转换(16)
| 函数 | 作用 | |
|---|---|---|
| 1 | bool() | 将给定参数转换为布尔类型,True 或者 False |
| 2 | int() | 返回一个基于数字或字符串 x 构造的整数对象 |
| 3 | float() | 返回从数字或字符串 x 生成的浮点数。 |
| 4 | complex() | 根据传入的参数创建一个新的复数 |
| 5 | str() | 返回一个 str版本的 object |
| 6 | bytearray() | 返回一个新的 bytes 数组 |
| 7 | bytes() | 返回一个新的“bytes”对象 |
| 8 | memoryview() | 创建一个新的内存查看对象 |
| 9 | list() | 根据传入的参数创建一个新的列表 |
| 10 | tuple() | 根据传入的参数创建一个新的元组 |
| 11 | dictionary() | 根据传入的参数创建一个新的字典 |
| 12 | set() | 根据传入的参数创建一个新的集合 |
| 13 | frozenset() | 根据传入的参数创建一个不可变集合 |
| 14 | slice() | 创建一个新的切片类型对象 |
| 15 | super() | 创建一个新的子类和父类关系的代理对象 |
| 16 | object() | 创建一个新的object对象 |
# bool:根据传入的参数的逻辑值
>>> bool() #未传入参数
False
>>> bool(0) #数值0、空序列等值为False
False
>>> bool(1)
True
# ------------------------------------------------------------
# int:根据传入的参数创建一个新的整数
>>> int() #不传入参数时,得到结果0。
0
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16) # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制
18
# ------------------------------------------------------------
# float:根据传入的参数创建一个新的浮点数
>>> float('3')
3.0
# ------------------------------------------------------------
frozenset() 不能在添加删除元素
a = frozenset(range(10)) # 先创建一个冻结集合
print(a)
# frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
del a[0]
# TypeError: 'frozenset' object doesn't support item deletion
字符转换(6)
| 函数 | 作用 | |
|---|---|---|
| 1 | ord() | 返回对应字符的ascii码 |
| 2 | chr() | 返回ascii码对应的字符 |
| 3 | bin() | 将整数转化为2进制字符串 |
| 4 | oct() | 将整数转化为8进制字符串 |
| 5 | hex() | 将整数转化为16进制字符串 |
| 6 | ascill() | 转义非 ASCII 字符 |
# ------------------------------------------------------------
# ord() ord()函数是chr()的配对函数
print( ord('b') ) # 返回:98
print( ord('%') ) # 返回:37
# 把数字98在ascii码中对应的字符打印出来
print( chr(98) ) # 返回:b
# ------------------------------------------------------------
# bin()函数返回一个整数int或者长整数long int的二进制
print( bin(10) ) # 0b1010
print( bin(133) ) # 0b10000101
# ------------------------------------------------------------
# oct() 整数转八进制
print( oct(10) ) # 0o12
print( oct(255) ) # 0o377
print( oct(-6655) ) # -0o14777
# ------------------------------------------------------------
print(hex(1)) # 0x1
print(hex(-256)) # -0x100
print(type(hex(-256))) #<class 'str'>
序列操作(8)
| 函数 | 作用 | |
|---|---|---|
| 1 | all() | 所有元素存在且不为空,0 返回True |
| 2 | any() | 存在元素存在, 0也可以,返回为True |
| 3 | filter() | 过滤序列,过滤可迭代对象的元素 |
| 4 | map() | 使用指定方法取作用传入的每个迭代对象的元素,生成新的可迭代对象 |
| 5 | next() | 返回可迭代对象的下一个元素值 |
| 6 | reversed() | 反转序列生成新的可迭代对象 |
| 7 | sorted() | 对可迭代对象进行排序,返回一个新的列表 |
| 8 | zip() | 聚合传入的每隔迭代器中的相同位置的元素,返回一个新的元祖类型迭代器 |
all(['a', 'b', 'c', 'd']) # 列表list,元素都不为空或0
# True
all(['a', 'b', '', 'd']) # 列表list,存在一个为空的元素
# False
# ------------------------------------------------------------
any(['a', 'b', '', 'd']) # 列表list,存在一个为空的元素
# True
any([0, '', False]) # 列表list,元素全为0,'',false
False
# ------------------------------------------------------------
def is_odd(n):
return n % 2 == 1
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)
[1, 3, 5, 7, 9]
# ------------------------------------------------------------
def square(x) : # 计算平方数
return x ** 2
res=map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
print(res)
# [1, 4, 9, 16, 25]
# ------------------------------------------------------------
bb = [1,3,5,7]
print(reversed(bb))
# <list_reverseiterator object at 0x0000029336879E48>
print(list(reversed(bb)))
# [7,5,3,1]
# ------------------------------------------------------------
a=[1,2,3]
b=['a','c','d','e']
zz=zip(a,b)
print(zz)
print(list(zz))
x,y=zip(*[[1,2],[3,4],[5,6]])
print(x)
print(y)
#<zip object at 0x000001457B3375C8>
#[(1, 'a'), (2, 'c'), (3, 'd')]
#(1, 3, 5)
#(2, 4, 6)
遍历迭代生成器(4)
| 函数 | 作用 | |
|---|---|---|
| 1 | range() | 根据传入的参数创建一个新的range对象 |
| 2 | iter() | 生成迭代器 |
| 3 | next() | 回可迭代对象的下一个元素值 |
| 4 | enumerate() | 根据可迭代对象创建枚举对象 |
list1=range(5)
print(list(list1)) # [0,1,2,3,4]
# ------------------------------------------------------------
# iter()
#list、tuple等都是可迭代对象,我们可以通过iter()函数获取这些可迭代对象的迭代器
it = [1,2,3]
it_list = iter(it)
print(next(it_list))
1
# ------------------------------------------------------------
# next()
it = iter([1,2,3,4,5])
print(next(it))
1
# ------------------------------------------------------------
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
# 返回:[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
面向对象(11)
| 函数 | 作用 | |
|---|---|---|
| 1 | help() | 返回对象的帮助信息 |
| 2 | dir() | 返回对象或者当前作用域内的属性列表 |
| 3 | id() | 返回对象的唯一标识符 |
| 4 | hash() | 获取对象的哈希值 |
| 5 | type() | 元类,类的最高层 |
| 6 | len() | 返回对象的长度 |
| 7 | format() | 格式化显示值 |
| 8 | vars() | 返回当前作用域内的局部变量,和其值组成的字典,或者返回对象的属性列表 |
| 装饰器 | ||
| 9 | classmethod | 标示方法为类方法的装饰器 |
| 10 | staticmethod | 标示方法为静态方法的装饰器 |
| 11 | property | 标示属性的装饰器 |
help()
a = [1,2,3]
help(a) # 查看列表 list 帮助信息
help(a.append) # 显示list的append方法的帮助
# ------------------------------------------------------------
dir()
# ------------------------------------------------------------
id()
a = "123" # 字符串
print(id(a)) # 13870392
b = [1,2,3] # 列表
print(id(b)) # 7184328
# ------------------------------------------------------------
hash() # 获取一个对象(数字或者字符串等)的哈希值。不能直接应用于 list、set、dictionary
print(hash(1)) # 1
print(hash(20000)) # 20000
print(hash('123')) # -6436280630278763230
print(hash('ab12')) # 5468785079765213470
print(hash('ab12')) # 5468785079765213470
# ------------------------------------------------------------
# len()
print(len('1234')) # 字符串,返回字符长度4
print(len(['1234','asd',1])) # 列表,返回元素个数3
print(len((1,2,3,4,50))) # 元组,返回元素个数5
# ------------------------------------------------------------
fromt()
print('name:{n},url:{u}'.format(n='alex',u='www.xxxxx.com'))
# name:alex,url:www.xxxxx.com
反射操作(8)
| 1 | __import__ | 动态导入模块 |
| 2 | isinstance() | 判断对象是否是类或者类型 |
| 3 | issubclass() | 判断类是否是另外一个类子类 |
| 4 | hasattr() | 检查对象是否含有属性 |
| 5 | getattr | 获取对象的属性值 |
| 6 | setattr | 设置对象的属性值 |
| 7 | delattr | 删除对象的属性 |
| 8 | callable | 检测对象是否可被调用 |
# # ------------------------------------------------------------
# isinstance()
print(isinstance(a,int)) # True
print(isinstance(a,str)) # False
print(isinstance(a,(str,tuple,dict))) # False
# # ------------------------------------------------------------
issubclass()
class A:
pass
class B(A): # b继承了a,即b是a的子类
pass
print(issubclass(A,B)) # 判断 a 是 b 的子类?
# False
print(issubclass(B,A)) # 判断 b 是 a 的子类?
# True
# # ------------------------------------------------------------
hasattr()
list_list=[]
print(hasattr(list_list, 'append'))
True
print(hasattr(list_list, 'add'))
False
# # ------------------------------------------------------------
class Test():
name="ming"
def run(self):
return "Hello World"
t=Test()
getattr()
# # ------------------------------------------------------------
# callable()函数用于检查一个对象是否可调用的
def sayhi():pass # 先定义一个函数sayhi()
print( callable( sayhi ) ) # True
-
isinstance() 与 type() 区别:
type()不会认为子类是一种父类类型,不考虑继承关系。isinstance()会认为子类是一种父类类型,考虑继承关系。 如果要判断两个类型是否相同推荐使用isinstance()。
作用域相关(2)
| 函数 | 作用 | |
|---|---|---|
| 1 | globals() | 返回当前位置的全部全局变量 ,字典类型 |
| 2 | locals() | 以字典类型返回当前位置的全部局部变量 |
def function(arg): # 两个局部变量:arg、z
z = 1
print (locals())
function(4)
# {'z': 1,'arg':4}
a = 1
print(globals())
# {'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
# 多一个 a:1
交互操作(2)
| 函数 | 作用 | |
|---|---|---|
| 1 | print() | 向标准输出对象打印输出 |
| 2 | inpurt() | 读取用户输入值 |
>>> print(1,2,3,sep = '+',end = '=?')
1+2+3=?
s = input('please input your name:')
please input your name:Ain
>>> s
'Ain'
文件操作(1)
| 函数 | 作用 | |
|---|---|---|
| 1 | open() | 使用指定的模式和编码打开文件,返回文件读写对象 |
>>> a = open('test.txt','rt')
>>> a.read()
'some text'
>>> a.close()
编译执行(4)
| 函数 | 作用 | |
|---|---|---|
| 1 | compile | 将字符串编译为代码或者AST对象,使之能够通过exec语句来执行或者eval进行求值 |
| 2 | eval() | 执行动态表达式求值 |
| 3 | exec() | 执行动态语句块 |
| 4 | repr | 函数将对象转化为供解释器读取的形式 |
str = "for i in range(0,10): print(i,end=' ')"
c = compile(str, '', 'exec')
exec(c)
# 输出
0 1 2 3 4 5 6 7 8 9
# # ------------------------------------------------------------
# eval() 函数用来执行一个字符串表达式
print(eval('3 * 2')) # 6
# # ------------------------------------------------------------
# exec() 执行储存在字符串或文件中的Python语句
exec("print('Hello World')") # 执行简单的字符串
# Hello World
exec("for i in range(5): print('iter time is %d'%i)") # 执行复杂的for循环
# iter time is 0
# iter time is 1
# iter time is 2
# iter time is 3
# iter time is 4
# ----------------------------------------------
# repr() 将对象转化为供解释器读取的形式。返回一个对象的 string 格式
r = repr((1,2,3))
print( r ) # (1, 2, 3)
print( type(r) ) # <class 'str'>
dict = repr({'a':1,'b':2,'c':3})
print( dict ) # {'c': 3, 'a': 1, 'b': 2}
print( type(dict) ) # <class 'str'>