python内置函数大全及其用法:python内置函数汇总五分钟学会
python内置函数大全及其用法:python内置函数汇总五分钟学会•对象操作(7个)•序列操作(8个)为了方便记忆,将python3.5中的所有内置函数进行如下分类:•数学运算(7个)•类型转换(24个)
内置函数在python中占有非常重要的地位,熟练掌握它,是我们学好,用好python的第一步,使用它可以加快我们编写代码的效率。
创作人:码农阿勇
编写约定:1.函数名后带"*"的要重点掌握,2.带>>>表示待执行的语句,不带的表示执行果。
我们会陆续推出python编程方面的文章,希望大家多多关注。
为了方便记忆,将python3.5中的所有内置函数进行如下分类:
•数学运算(7个)
•类型转换(24个)
•序列操作(8个)
•对象操作(7个)
•反射操作(8个)
•变量操作(2个)
•交互操作(2个)
•文件操作(1个)
•编译执行(4个)
•装饰器(3个)
一、数学运算:********
abs:求数值的绝对值
>>>abs(-2)
2
divmod:返回两个数值的商和余数
>>> divmod(10 3)
(3 1)
max:*返回可迭代对象的元素中的最大值或者所有参数的最大值
>>>max(11 1 2 13 4)
13
>>>max([23 1 222 13 4])
222
>>>max(-1 0 key=abs) #传入了求绝对值函数,则参数都会进行求绝对值后再取较大者
-1
>>>max('1245657')
7 #传入1个可迭代对象,取其最大元素值
min:*返回可迭代对象的元素中的最小值或者所有参数的最小值(其他用法同上)
>>>min(11 12 3 4 5)
3
pow:取两个值的幂运算值,或与其他
>>> pow(2 3)
8
>>>pow(10 2 7) #取(10**2)%5 取模就是余数
2
round:*对浮点数进行四舍五入求值(四舍六入五取偶)
>>> round(1.456778888)
1
>>>round(1.4567787888 2)#这里的2是保留小数位数,默认保留一位
1.46
print(round(1.5))>>>2
print(round(2.5))>>>2
print(round(3.5))>>>4
print(round(4.5))>>>4
sum:*对元素类型是数值的可迭代对象中的每个元素求和
sum(iteable [ start])#有起始值了将起始值也加到迭代类型的和中。
>>>sum((1 2 3 4))
10
>>> sum([1 2 3 4])
10
>>>sum((1 2 3 4) 3)
13
>>> sum((1 2 3 4) -3)
7
二、类型转换*******
bool:*根据传入的参数的逻辑值创建一个新的布尔值
print(bool(0) bool(1))>>>False True
print(bool(None))>>>False
print(bool([]) bool([11 33]))>>>False True
print(bool(()) bool((11 33)))>>>False True
print(bool({}) bool({"s":23}))>>>False True
int:*根据传入的参数创建一个新的十进制整数
int(x [ base])#默认按十进制转换
>>> int() #不传入参数时,得到结果0。
0
>>> int(3)
3
>>> int(3.6)
3
>>> int("0b1101" 2)#将指定的第一个参数按2进制进行转换为十进制
13
>>>int("0x10" 16)#将指定的第一个参数按2进制进行转换为十进制
16
float:*根据传入的参数创建一个新的浮点数
>>> float() #不提供参数的时候,返回0.0
0.0
>>> float(3)
3.0
>>> float('3')
3.0
str:*返回一个对象的字符串表现形式(给用户)
>>> str()
''
>>> str(None)
'None'
>>> str('abc')
'abc'
>>> str(123)
'123'
temp=str({"12":33})
print(type(temp))>>>str
bin:将整数转换成2进制字符串
>>>bin(12)
0b1100
>>>bin(0x12)
0b10010
oct:将整数转化成8进制数字符串
>>> oct(10)
'0o12'
hex:将整数转换成16进制字符串
>>> hex(15)
'0xf'
>>> hex(0b1100)
'0xc'
bytes:*根据传入的参数创建一个新的不可变字节数组
bytes(string encoding[ errors]) -> bytes
>>> bytes('中文' 'utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
ord:*返回Unicode字符对应的整数
>>> ord('a')
97
chr:*返回整数所对应的Unicode字符
>>> chr(97) #参数类型为整数
'a'
tuple:*根据传入的参数(为空或可迭代类型)创建一个新的元组
>>> tuple() #不传入参数,创建空元组
()
>>> tuple('121') #传入可迭代对象。使用其元素创建新的元组
('1' '2' '1')
>>>tuple([11 22 33]
(11 22 33)
list:*根据传入的参数创建一个新的列表
>>>list() # 不传入参数,创建空列表
[]
>>> list('abcd') # 传入可迭代对象,使用其元素创建新的列表
['a' 'b' 'c' 'd']
dict:*根据传入的参数创建一个新的字典
>>> dict() # 不传入任何参数时,返回空字典。
{}
>>> dict(a = 1 b = 2) # 可以传入键值对创建字典。
{'b': 2 'a': 1}
>>> dict(zip(['a' 'b'] [1 2])) # 可以传入映射函数创建字典。
{'b': 2 'a': 1}
>>> dict((('a' 1) ('b' 2))) # 可以传入可迭代对象创建字典。
{'b': 2 'a': 1}
set:*根据传入的参数创建一个新的集合
>>>set() # 不传入参数,创建空集合
set()
>>> a = set(range(10)) # 传入可迭代对象,创建集合
>>> a
{0 1 2 3 4 5 6 7 8 9}
>>>set([11 22 33 11])#set集合中的元素不允许重复,是一个无序的集合
{33 11 22}
enumerate:根据可迭代对象创建枚举对象
>>> seasons = ['Spring' 'Summer' 'Fall' 'Winter']
>>> list(enumerate(seasons))
[(0 'Spring') (1 'Summer') (2 'Fall') (3 'Winter')]
>>> list(enumerate(seasons start=1)) #指定起始值
[(1 'Spring') (2 'Summer') (3 'Fall') (4 'Winter')]
for i in enumerate([11 22 33 44]):
print(i)
>>> (0 11)
(1 22)
(2 33)
(3 44)
range:*根据传入的参数创建一个新的range对象
>>> a = range(10)
>>> b = range(1 10)
>>> c = range(1 10 3)
>>> a b c # 分别输出a b c
(range(0 10) range(1 10) range(1 10 3))
>>> list(a) list(b) list(c) # 分别输出a b c的元素
([0 1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9] [1 4 7])
iter:根据传入的参数创建一个新的可迭代对象
>>> a = iter('abcd') #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
File "<pyshell#29>" line 1 in <module>
next(a)
StopIteration
super:根据传入的参数创建一个新的子类和父类关系的代理对象
>> class A(object):
def __init__(self):
print('A.__init__')
#定义子类B,继承A
>>> class B(A):
def __init__(self):
print('B.__init__')
super().__init__()
#super调用父类方法
>>> b = B()
B.__init__
A.__init__
slice:根据传入的参数创建一个新的切片对象
主要用在切片操作函数里的参数传递
class slice(start stop[ step])
start:起始位置
stop:结束位置
step:间距
c2 = slice(5)#它会返回一个切片对象
c1=list(range(10))
print(c1[c2])>>>[0 1 2 3 4]
三、序列操作*******
next:返回可迭代对象中的下一个元素值
>>> a = iter('abcd')
>>> next(a)
'a'
>>> next(a)
'b'
all:*判断的可迭代对象的每个元素是否都为True值
>>> all([1 2]) #列表中每个元素逻辑值均为True,返回True
True
>>> all([0 1 2]) #列表中0的逻辑值为False,返回False
False
>>> all(()) #空元组
True
>>> all({}) #空字典
True
any:*判断可迭代对象的元素是否有为True值的元素
>>> any([0 1 2]) #列表元素有一个为True,则返回True
True
>>> any([0 0]) #列表元素全部为False,则返回False
False
>>> any([]) #空列表
False
>>> any({}) #空字典
False
filter:*使用指定方法过滤可迭代对象的元素
>>> a = list(range(1 10)) #定义序列
>>> a
[1 2 3 4 5 6 7 8 9]
>>> def if_odd(x): #定义奇数判断函数
return x%2==1
>>> list(filter(if_odd a)) #筛选序列中的奇数
[1 3 5 7 9]
temp=filter(lambda x:type(x)==int [1 2 3 "peng" 4 "tong" 78])
print(list(temp))
temp=filter(lambda x:x>66 [1 2 67 78 43 99])
print(list(temp))
#对传入的列表,返回奇数索引为的元素并返回给调用者
def ft(a):
temp=filter(lambda x:a.index(x)%2!=0 a)
return temp
print(list(ft([2 5 8 12 4])))
map:*使用指定方法去作用传入的每个可迭代对象的元素,生成新的可迭代对象
>>> a = map(ord 'abcd')
>>> a
<map object at 0x03994E50>
>>> list(a)
[97 98 99 100]
p=map(lambda x:x*x [1 2 3 4])
print(list(p) type(p))
p=map(lambda x:str(x) [1 2 3 4])
print(list(p) type(p))
tt=map(lambda x y z:x y z [1 2 3] [1 2 3] [1 2 3])
print(list(tt))
sorted:*对可迭代对象进行排序,返回一个新的列表
a=[44 11 22 5 99 8]
temp=sorted([11 3 98])
print(temp)
dt={"lenovo":123 "huaweix":78 "zhongxing":100}
pp=sorted(dt.values())
print(pp)
#对字典安装值排序
pp=sorted(dt.items() key=lambda x:x[1])
print(pp)
#对字典安装键名长度排序
pp=sorted(dt.items() key=lambda x:len(x[0]))
print(pp)>>>[('lenovo' 123) ('huaweix' 78) ('zhongxing' 100)]
#安装字符的unicode码排序
pp=sorted("徐姜维" key=lambda x:ord(x))
print(pp)
def f(x):
return ord(x)
#按字符的unicode码从大到小排
pp=sorted("徐姜维" key=f reverse=True)#
print(pp "sdf")
reversed:反转序列生成新的可迭代对象
>>> a = reversed(range(10)) # 传入range对象
>>> a # 类型变成迭代器
<range_iterator object at 0x035634E8>
>>> list(a)
[9 8 7 6 5 4 3 2 1 0]
zip:*聚合传入的每个迭代器中相同位置的元素,返回一个新的元组类型迭代器
>>> x = [1 2 3] #长度3
>>> y = [4 5 6 7 8] #长度5
>>> list(zip(x y)) # 取最小长度3
[(1 4) (2 5) (3 6)]
四、对象操作*******
help:*返回对象的帮助信息
>> help(str)
Help on class str in module builtins:
class str(object)
| str(object='') -> str
| str(bytes_or_buffer[ encoding[ errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self value /)
| Return self value.
|
***************************
dir:*返回对象或者当前作用域内的属性列表
>>>dir(list)
['__add__' '__class__' '__contains__' '__delattr__' '__delitem__' '__dir__'
'__doc__' '__eq__' '__format__' '__ge__' '__getattribute__' '__getitem__' '
__gt__' '__hash__' '__iadd__' '__imul__' '__init__' '__iter__' '__le__' '
__len__' '__lt__' '__mul__' '__ne__' '__new__' '__reduce__' '__reduce_ex__'
'__repr__' '__reversed__' '__rmul__' '__setattr__' '__setitem__' '__sizeof__'
'__str__' '__subclasshook__' 'append' 'clear' 'copy' 'count' 'extend'
'index' 'insert' 'pop' 'remove' 'reverse' 'sort']
id:返回对象的唯一标识符
>>> a = 'some text'
>>> id(a)
69228568
type:*返回对象的类型,或者根据传入的参数创建一个新的类型
>>> type(23) # 返回对象的类型
<class 'int'>
len:*返回对象的长度
>>> len('abcd') # 字符串
>>> len(bytes('abcd' 'utf-8')) # 字节数组
>>> len((1 2 3 4)) # 元组
>>> len([1 2 3 4]) # 列表
>>> len(range(1 5)) # range对象
>>> len({'a':1 'b':2 'c':3 'd':4}) # 字典
>>> len({'a' 'b' 'c' 'd'}) # 集合
format:格式化显示值
#字符串可以提供的参数 's' None
>>> format('some string' 's')
'some string'
>>> format('some string')
'some string'
#整形数值可以提供的参数有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
>>> format(3 'b') #转换成二进制
'11'
>>> format(97 'c') #转换unicode成字符
'a'
>>> format(11 'd') #转换成10进制
'11'
>>> format(11 'o') #转换成8进制
'13'
>>> format(11 'x') #转换成16进制 小写字母表示
'b'
>>> format(11 'X') #转换成16进制 大写字母表示
'B'
>>> format(11 'n') #和d一样
'11'
>>> format(11) #默认和d一样
'11'
#浮点数可以提供的参数有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None
>>> format(314159267 'e') #科学计数法,默认保留6位小数
'3.141593e 08'
>>> format(314159267 '0.2e') #科学计数法,指定保留2位小数
'3.14e 08'
>>> format(314159267 '0.2E') #科学计数法,指定保留2位小数,采用大写E表示
'3.14E 08'
>>> format(314159267 'f') #小数点计数法,默认保留6位小数
'314159267.000000'
>>> format(3.14159267000 'f') #小数点计数法,默认保留6位小数
'3.141593'
>>> format(3.14159267000 '0.8f') #小数点计数法,指定保留8位小数
'3.14159267'
>>> format(3.14159267000 '0.10f') #小数点计数法,指定保留10位小数
'3.1415926700'
>>> format(3.14e 1000000 'F') #小数点计数法,无穷大转换成大小字母
'INF'
#g的格式化比较特殊,假设p为格式中指定的保留小数位数,先尝试采用科学计数法格式化,得到幂指数exp,如果-4<=exp<p,则采用小数计数法,并保留p-1-exp位小数,否则按小数计数法计数,并按p-1保留小数位数
>>> format(0.00003141566 '.1g') #p=1 exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
'3e-05'
>>> format(0.00003141566 '.2g') #p=1 exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留1位小数点
'3.1e-05'
>>> format(0.00003141566 '.3g') #p=1 exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留2位小数点
'3.14e-05'
>>> format(0.00003141566 '.3G') #p=1 exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点,E使用大写
'3.14E-05'
>>> format(3.1415926777 '.1g') #p=1 exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留0位小数点
'3'
>>> format(3.1415926777 '.2g') #p=1 exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留1位小数点
'3.1'
>>> format(3.1415926777 '.3g') #p=1 exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
'3.14'
>>> format(0.00003141566 '.1n') #和g相同
'3e-05'
>>> format(0.00003141566 '.3n') #和g相同
'3.14e-05'
>>> format(0.00003141566) #和g相同
'3.141566e-05'
五、反射操作********
__import__:动态导入模块
index = __import__('index')
index.sayHello()
isinstance:*判断对象是否是类或者类型元组中任意类元素的实例
>>> isinstance(1 int)
True
>>> isinstance(1 str)
False
>>> isinstance(1 (int str))
True
hasattr:*检查对象是否含有属性
hasattr(obj name)
>>>hasattr(a "append")
True
>>> class Student:
def __init__(self name):
self.name = name
>>> s = Student('Aim')
>>> hasattr(s 'name') #a含有name属性
True
>>> hasattr(s 'age') #a不含有age属性
False
getattr:*获取对象的属性值
>>>a=[11 22]
>>>getattr(a "append")
<built-in method append of list object at 0x0000000002B45848>
>>>getattr(a "append")(44)
>>>a
[11 22 44]
定义类Student
>>> class Student:
def __init__(self name):
self.name = name
>>> getattr(s 'name') #存在属性name
'Aim'
>>> getattr(s 'age' 6) #不存在属性age,但提供了默认值,返回默认值
>>> getattr(s 'age') #不存在属性age,未提供默认值,调用报错
Traceback (most recent call last):
File "<pyshell#17>" line 1 in <module>
getattr(s 'age')
AttributeError: 'Stduent' object has no attribute 'age'
setattr:设置对象的属性值
>>> class Student:
def __init__(self name):
self.name = name
>>> a = Student('Kim')
>>> a.name
'Kim'
>>> setattr(a 'name' 'Bob')
>>> a.name
'Bob'
delattr:删除对象的属性
>>> class A:
def __init__(self name):
self.name = name
def sayHello(self):
print('hello' self.name)
#测试属性和方法
>>>a=A("小麦")
>>> a.name
'小麦'
>>> a.sayHello()
hello 小麦
#删除属性
>>> delattr(a 'name')
>>> a.name
Traceback (most recent call last):
File "<pyshell#47>" line 1 in <module>
a.name
AttributeError: 'A' object has no attribute 'name'
callable:*检测对象是否可被调用
>>> class B: #定义类B
def __call__(self):
print('instances are callable now.')
>>> callable(B) #类B是可调用对象
True
>>> b = B() #调用类B
>>> callable(b) #实例b是可调用对象
True
>>> b() #调用实例b成功
instances are callable now.
def test():
print("hehe")
>>>callable(test)
True
六、编译执行*********
compile:将字符串编译为代码或者AST对象,使之能够通过exec语句来执行或者eval进行求值
#我们一般不用,导入模块就是用该函数实现的
>>> #流程语句使用exec
>>> code1 = 'for i in range(0 10): print (i)'
>>> compile1 = compile(code1 '' 'exec')
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9
eval:执行动态表达式求值
>>> eval('1 2 3 4')
10
>>>eval('[11 22].pop(1)')
22
exec:执行动态语句块
>>> exec('a=1 2') #执行语句
>>> a
3
>>>a1="""a=1 2 3\nb=3 5"""
>>>exec(a1)
print(a b)
6 8
七、装饰器相关*****
property:标示属性的装饰器
classmethod:标示方法为类方法的装饰器
staticmethod:标示方法为静态方法的装饰器
八、交互操作(2个)*******
print:*向标准输出对象打印输出
>> print(1 2 3)
1 2 3
>>> print(1 2 3 sep = ' ')
1 2 3
>>> print(1 2 3 sep = ' ' end = '=?')
1 2 3=?
input:*读取用户输入值
>>> s = input('please input your name:')
please input your name:Ain
>>> s
'Ain'
九、文件操作*******
open:*使用指定的模式和编码打开文件,返回文件读写对象
常用的open语法格式:open(file mode encoding errors)
file:文件的路径
mode:文件操作模式
r #读
w:#写,写时如果文件存在则先清空原文件内容然后重写,不存在则创建文件再操作
a:#追加模式,不存在则创建文件,存在则在原文件内容末尾追加
r : w a 可读可写
rb wb ab 操作二进制文件比如图片 b为二进制读写
encoding:指定文件打开的文件编码类型,默认为GBK
errors:当打开文件错误时,是否忽略错误
>>> a = open('test.txt' 'rt')#读之前确保文件test真实存在
>>> a.read()
'some text'
>>> a.close()
十、变量操作**************
globals:返回当前作用域内的全局变量和其值组成的字典
locals:返回当前作用域内的局部变量和其值组成的字典