第十二篇 Python内置函数

300 阅读13分钟

1、数学运算类函数

abs,divmod,max,min,pow,round,sum

1、计算数值的绝对值:abs()

print(abs(-15)) 
-----输出结果---- 
15 

2、返回两个数的商和余数:divmod()

print(divmod(13,5)) 
 ------输出结果------
(2,3)

3、返回所有参数中元素的最大值或者返回可迭代对象中元素的最大值:max()

print(max(1,2,3))  #取三个数中的最大者 
print(max('123'))  #取可迭代对象中的最大者
print(max(-2,-1,0,key=abs)) #把-2-10依次传给abs的参数,然后把abs的结果返回给key,max依次比较key的大小 
-------输出结果-------
-2

4、返回所有参数中元素的最小值或者返回可迭代对象中元素的最小值:min()

 print(min(1,2,3))  #取三个数中的最小者 
 print(min('123'))  #取可迭代对象中的最小者 
 print(min(-2,-1,0,key=abs)) #把-2-10依次传给abs的参数,然后把abs的结果返回给key,max依次比较key的大小 
 -------输出结果-----
 1
 1
 0

5、返回两个数值的幂运算值或者其与指定值的余数:pow()

print(pow(2,4)) #2的4次幂 
print(pow(2,4,3)) #2的4次幂,然后除以3的余数 1
------输出结果-----
16
1

6、浮点数进行四舍五入:round()

print(round(2.563,1))  #2.563四舍五入,精度为1 
print(round(2.561654132,5)) #2.561654132四舍五入,精度为5
--------输出结果------
2.6
2.56165

7、参数类型为数值的可迭代对象中的每个元素求和:sum()

print(sum((1,2,3,4,5,6)))  #对可迭代对象进行求和
print(sum((1,2,3,4,5,6),16)) #可迭代对象的和与'start'的和 
--------输出结果-----
21
37

2、类型转换类函数

bool,int,float,complex,str,bytearray,bytes,memoryview,ord,chr,bin,oct,hex,tuple,list,dict,set,frozenset,enumerate,range,slice,super,object

1、根据传入的参数的值返回布尔值:bool()

 print(bool()) #不传递参数,返回False
 print(bool(0))
 print(bool(''))
 print(bool(())) # 0,'',()等为值的布尔值为False
 print(bool(2))

 ------输出结果------
 False
 False
 False
 False
 True

2、根据传入的参数值创建一个新的整数值:int()

 print(int())  #不传递参数时,结果为0 
 print(int(1.8)) #向下取整
 print(int('12')) #根据字符串类型创建整型

 -------输出结果------
 0
 1
12

3、根据传入的参数值创建一个新的浮点数值:float()

 print(float())  #不传递参数时,结果为0.0 
 print(float(1)) 
 print(float('12')) #根据字符串类型创建浮点值
 -------输出结果------
 0.0
 1.0
 12.0

4、根据传入的参数值创建一个新的复数值:complex()

 print(complex())  #不传递参数时,结果为0j
 print(complex(1))
 print(complex(1,3)) #1为实数部分,3为虚数部分 
 print(complex('12')) #根据字符串类型创建复数
 print(complex('1+2j')) 
 ------输出结果-----
 0j
 (1+0j)
 (1+3j)
 (12+0j)
 (1+2j)

5、返回一个对象的字符串表示形式,这个主要是给用户看:str()

>>> str(None)
'None'
>>> str('123')
'123'
>>> str(1234)
'1234'
>>> str()
''
>>>

6、根据传入的参数创建一个字节数组(可变):bytearray()

print(bytearray('博小园','utf-8')) 
------输出结果-----
bytearray(b'\xe5\x8d\x9a\xe5\xb0\x8f\xe5\x9b\xad')

7、根据传入的参数创建一个不变字节数组:bytes()

print(bytes('博小园','utf-8'))
 
 ------输出结果-----
b'\xe5\x8d\x9a\xe5\xb0\x8f\xe5\x9b\xad'

8、根据传入的参数创建一个内存查看对象:memoryview()

memview=memoryview(b'abcdef')
print(memview[0])
print(memview[-1])
--------输出结果--------
97
102

9、根据传入的参数返回对应的整数:ord()

print(ord('a'))

-------输出结果------
97

10、根据传入的参数的整数值返回对应的字符:chr()

print(chr(97))

-------输出结果------
a

11、根据传入的参数的值返回对应的二进制字符串:bin()

print(bin(12))

-------输出结果------
0b1100

12、根据传入的参数的值返回对应的八进制字符串:oct()

print(oct(12))
 
-------输出结果------
0o14

13、根据传入的参数的值返回对应的十六进制字符串:hex()

print(hex(12))
------输出结果-----
0xc

14、根据传入的参数创建一个tuple元组:tuple()

print(tuple())  #不传递参数,创建空元组 ()
print(tuple('12345')) #根据可迭代参数,创建元组

------输出结果-----
()
('1', '2', '3', '4', '5')

15、根据传入的参数创建一个新列表:list()

print(list())  #不传递参数,创建空列表 ()
print(list('12345')) #根据可迭代参数,创建列表
 
-------输出结果-------
[]
['1', '2', '3', '4', '5']

16、根据传入的参数创建一个新的字典:dict()

 print(dict())  #不传递参数,创建一个空的字典
 
 print(dict(x=2,y=7)) #传递键值对创建字典
 
 print(dict((('x',1),('y',3))))  #传入可迭代对象创建新的字典
 
 print(dict([('x',1),('y',7)]))
 print(dict(zip(['x','y'],[2,3])))  #传入映射函数创建新的字典
 
 ---------输出结果-----
 {}
 {'x': 2, 'y': 7}
 {'x': 1, 'y': 3}
 {'x': 1, 'y': 7}
 {'x': 2, 'y': 3}

17、根据传入的参数创建一个新的集合:set()

print(set()) #传入的参数为空,返回空集合
 
print(set(range(7)))  #传入一个可迭代对象,创建集合
-------输出结果-----
set()
{0, 1, 2, 3, 4, 5, 6}

18、根据传入的参数创建一个新的不可变集合:frozenset()

print(frozenset(range(8)))
 
-------输出结果------
frozenset({0, 1, 2, 3, 4, 5, 6, 7})

19、根据可迭代对象创建枚举对象:enumerate()

names=['zhangsan','lisi','wangwu','boxiaoyuan'] 
print(list(enumerate(names)))
print(list(enumerate(names,1)))
-------输出结果-----
[(0, 'zhangsan'), (1, 'lisi'), (2, 'wangwu'), (3, 'boxiaoyuan')]
[(1, 'zhangsan'), (2, 'lisi'), (3, 'wangwu'), (4, 'boxiaoyuan')]

20、根据传入的参数创建一个新的range对象:range()

 x=range(9) #08
 
 y=range(1,9) #18 步长为1
 
 z=range(1,9,2) #18 步长为2
 
 print(list(x))
 print(list(y))
 print(list(z))

 -------输出结果--------
 [0, 1, 2, 3, 4, 5, 6, 7, 8]
 [1, 2, 3, 4, 5, 6, 7, 8]
 [1, 3, 5, 7]

21、根据传入的参数创建一个新的迭代器对象:iter()

 x=iter('1234')
 print(x)
 
 print(next(x))
 print(next(x))
 print(next(x))
 print(next(x))
 print(next(x))
-------输出结果-------
<str_iterator object at 0x000001BE6D71B860>
1
2
3
4
Traceback (most recent call last):
   File "E:/pythontest/test06.py", line 8, in <module>
     print(next(x))
StopIteration

22、根据传入的对象创建一个新的切片对象:slice()

切片函数主要对序列对象进行切去对应元素。

a=[0,1,2,3,4,5,6,7,8,9]
 
s=slice(0,9,2)   #从start:0到stop:9,步长为step:2
print(a[s])

-------输出结果------
[0, 2, 4, 6, 8]

23、根据传入的参数创建一个新的子类和父类关系的代理对象:super()

 class A:
     def __init__(self):
         print("A.__init__")
  
 class B(A):
     def __init__(self):
         print("B.__init__")
         super().__init__()
 
b=B()

-------输出结果------
B.__init__
A.__init__

24、创建一个新的object对象:object()

a=object()
a.name='boxiaoyuan'  #不能设置属性,object没有该属性

--------输出结果-------
Traceback (most recent call last):
  File "E:/pythontest/test06.py", line 2, in <module>
    a.name='boxiaoyuan'
AttributeError: 'object' object has no attribute 'name'

3、序列操作类函数

all,any,filter,map,next,reversed,sorted,zip

1、判断每个可迭代对象的每个元素的值是否都是True,都是Ture,则返回True:all()

 print(all([1,2,3,4,6]))  #列表中的每个元素的值都为True,则返回True
 
 print(all([0,2,3,4,5,6])) 
 
 print(all({})) #空字典返回True
 
 print(all(())) #空元组返回True
 
 ------输出结果------
True
False
True
True

2、判断可迭代对象的每个元素的值是否存在为True,存在则返回True:any()

 print(any([1,2,3,4,6]))  #列表中的存在一个为True,则返回True
 
 print(any([0,0]))
 
 print(any({})) #空字典返回False
 
 print(any(())) #空元组返回False
 
 -------输出结果------
 True
 False
 False
 False

3、使用指定方法过滤可迭代对象的元素:filter()

 lists=[0,1,2,3,4,5,6,7,8,9]
 
 def is_odd(x):
     if x%2==1:
         return x
 
 print(list(filter(is_odd,lists)))
 
 -------输出结果-------
[1, 3, 5, 7, 9]

4、使用指定方法作用传入的每个可迭代对象的元素,生成新的可迭代对象:map()

x=map(ord,'12345')

print(x)

print(list(x))

 -------输出结果-----
<map object at 0x0000026B7296B860>
[49, 50, 51, 52, 53]

5、返回可迭代对象的下一个对象:next()

a=[0,1,2]
it=a.__iter__()
print(next(it))
print(next(it))
print(next(it))
print(next(it,3))  #传入default,当还有元素值没有迭代完,则继续迭代,如果已经迭代完,则返回默认值

-------输出结果--------
0
1
2
3

6、反转序列生成的可迭代对象:reversed()

a=range(10)
print(a)  #可迭代对象
print(list(reversed(a)))

-------输出结果------
range(0, 10)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

7、对可迭代对象进行排序:sorted()

 a=[0,2,1,9,5,7,4]
 print(list(sorted(a)))  
 b=['a','c','d','A','C','D'] 
 print(list(sorted(b,key=str.lower)))
 
 -------输出结果-----
[0, 1, 2, 4, 5, 7, 9]
['a', 'A', 'c', 'C', 'd', 'D']

8、聚合传入的每个迭代器的相同位置的元素值,然后染回元组类型迭代器:zip()

x=[1,2,3]
y=[4,5,6,7,8]
 
print(list(zip(x,y)))

-------输出结果------
[(1, 4), (2, 5), (3, 6)]

4、对象操作类函数

help,dir,id,hash,type,len,ascii,format,vars

1、获取对象的帮助信息:help()

class list(object)
 |  list(iterable=(), /)
 |  
 |  Built-in mutable sequence.
 |  
 |  If no argument is given, the constructor creates a new empty list.
 |  The argument must be an iterable if specified.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 ...

2、获取对象和当前作用域的属性列表:dir()

import math

print(dir(math)) 
-----输出结果-----
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

3、返回对象的唯一标识符:id()

name='boxiaoyuan'
print(id(name))
 
------输出结果------
2125819230512

4、获取对象的hash码:hash()

name='boxiaoyuan'
print(hash(name))

-------输出结果------
1195266938384538974

5、根据参数返回参数的类型或者返回创建的新的对象:type()

 print(type(1))
 class A(object):
     name='zhangsan'
 
 class B(object):
     name='lisi'
 
 cObject=type('C',(A,B),{'name':'boxiaoyuan'}) #第一个参数是一个新的对象的名称,第二个参数是基类,第三个参数是属性
 print(cObject.name)

-------输出结果-----
<class 'int'>
boxiaoyuan

6、查看对象的长度:len()

 print(len('abcde'))
 print(len({'a':1}))
 print(len((1,2,3,4)))
 ------输出结果------
 5
 1
 4

7、调用对象的__repr__,获取该方法的返回值:ascii()

 class Person:
    def __repr__(self):
        return "hello world"
 
 
if __name__ == '__main__':
    person = Person()
    print(ascii(person))

8、返回对象的格式化值:format()

 #1.通过位置
 x='a={} b={} c={}'.format('zhangsan','lisi','boxiaoyuan') #{} 不带参数
 print(x)
 y='a={1} b={0} c={2}'.format('zhangsan','lisi','boxiaoyuan') #{} 带参数
 print(y)
 #2.通过关键字参数
 z='my English name is {name},my age is {age}'.format(name='boxiaoyuan',age='3')
 print(z)
 #3.通过对象属性
class Person:
    def __init__(self,name,age):
        self.name=name
        self.age=age

p=Person('boxiaoyuan',3)
print('name={p.name},age={p.age}'.format(p=p))
#4.通过下标
a1=[1,2,3,4]
a2=['a','b','c']

print('{0[0]},{1[1]}'.format(a1,a2))
#5.格式化输出
print('左对齐定长10位 [{:<10}]'.format(13))  #对齐与填充
print('右对齐定长10位 [{:>10}]'.format(13))
print('右对齐定长10位,以0填充 [{:0>10}]'.format(13))
 
print('[{:.2f}]'.format(13.123456)) #小数点输出
print('[{:,}]'.format(12345.1234567))#以逗号分割金额

print('10转换为2进制:{:b}'.format(10))  #进制转换

-------输出结果------
a=zhangsan b=lisi c=boxiaoyuan
a=lisi b=zhangsan c=boxiaoyuan
my English name is boxiaoyuan,my age is 3
name=boxiaoyuan,age=3
1,b
左对齐定长10位 [13        ]
右对齐定长10位 [        13]
右对齐定长10位,以0填充 [0000000013]
[13.12]
[12,345.1234567]
10转换为2进制:1010

9、返回当前作用域的局部变量和对象的属性列表和值:vars()

 name='zhangsan'
 print(vars())  #不传入参数时和locals等效,
 print(locals())
 class A(object):
     name='boxiaoyaun'
 
 
 print(vars(A))
 
-------输出结果------
{'name': 'zhangsan', '__cached__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/pythontest/test06.py', '__name__': '__main__', '__package__': None, '__spec__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000020E15CF6BE0>}
{'name': 'zhangsan', '__cached__': None, '__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/pythontest/test06.py', '__name__': '__main__', '__package__': None, '__spec__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000020E15CF6BE0>}
{'name': 'boxiaoyaun', '__module__': '__main__', '__doc__': None, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>}

5、交互类函数

input,print

1、键盘输入:input()

password = input("请输入您的银行卡密码:")
print(password) 
-----输出结果-----
请输入您的银行卡密码:123456
123456

2、输出到控制台:print()

%被称为格式化操作符,专门用于处理字符串中的格式。

格式化输出:

格式解释备注
%d整数%06d,表示显示如果显示的数字不够6位前面用0填充
%f浮点数%.2f表示小数点后只显示两位
%s字符串 
%%输出百分号 
 name = "小明"
 print("hello %s" % name)
 age = 18
 print("小明, 你的学号是:%06d" % 45)
 price = 2.56
 weight = 12
 total = price * weight
 print("小明,苹果的单价是%.2f,你买了%.2f斤,共%.2f元" % (price,weight,total))
 
--------输出结果------
hello 小明
小明, 你的学号是:000045
小明,苹果的单价是2.56,你买了12.00斤,共30.72元

  在默认情况下,print函数输出内容之后,会自动在内容末尾增加换行,如果不希望末尾添加换行,可以在print函数输出内容的后面增加,end="",其中""中间可以指定print函数输出内容之后,继续希望显示的内容。

语法格式如下:

# 向控制台输出内容结束之后,不会换行
print("*",end="")
 
# 单纯的换行
print("")

6、编译执行类函数

eval,exec,repr,compile

1、将字符串当成有效的表达式来求值并返回计算结果:eval()

  eval剥去字符串的外衣运算里面的代码。

1 print(eval('1 + 1'))

  在开发时不要使用eval直接转换input的结果,因为这样可以使用户任意执行操作系统命令,不安全。

2、执行动态语句块:exec()

  exec()与eval几乎一样,执行代码流。

exec('x = 3+6')
print(x)

3、返回对象的字符串表现形式给解释器:repr()

In [1]: a = 'test text'

In [2]: str(a)
Out[2]: 'test text'

In [3]: repr(a)
Out[3]: "'test text'"

In [4]:

4、将字符串编译为可以通过exec进行执行或者eval进行求值:complie()

code = 'for a in range(1, 7): print(a)'
comp = compile(code, '', 'exec')  # 流程的语句使用exec
exec(comp)
code1 = '1 + 2 + 3 + 4'
comp1 = compile(code1, '', 'eval')  # 求值使用eval
print(eval(comp1))

7、文件操作类函数

open,globals,locals

1、打开文件,并返回文件对象:open()

with open("d:test.txt", "r") as file:
    for line in file:
        print(line, end="")

8、变量操作类函数

1、获取当前作用域的全局变量和值的字典:globals()

>>> globals()
{'__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>}
>>> a = 4
>>> globals()
{'__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': '__main__', '__spec__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 4}

2、获取当前作用域的局部变量和值的字典:locals()

 >>> def func():
 ...     print('before a')
 ...     print(locals())
 ...     a = 2
 ...     print('after a')
 ...     print(locals())
 ...
 >>> func()
 before a
 {}
 after a
 {'a': 2} 13 >>>

9、反射操作类函数

__import__,isinstance,issubclass,hasattr,getattr,setattr,delattr,callable

1、动态导入模块:import()

time = __import__("time")
now = time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S", now))

2、判断对象是否是给定类的实例:isinstance()

In [1]: isinstance(1, int)
Out[1]: True

In [2]: isinstance('2', (int, str))
Out[2]: True

3、判断类是否为给定类的子类:issubclass()

In [1]: issubclass(bool, int)
Out[1]: True

In [2]: issubclass(bool, (int, str))
Out[2]: True

In [3]:

4、判断对象是有含有给定属性:hasattr();获取对象的属性值:getattr();设置对象的属性值:setattr();删除对象的属性值:delattr()

 In [1]: class Person:
    ...:     def __init__(self, name):
    ...:         self.name = name
    ...:
  
 In [2]: p = Person('zhangsan')
 
 In [3]: hasattr(p,'name')
 Out[3]: True
 In [4]: getattr(p, 'name')
 Out[4]: 'zhangsan'
 
 In [5]: setattr(p, 'name','lisi')
 In [6]: getattr(p, 'name')
 Out[6]: 'lisi'
 
 In [7]: delattr(p, 'name')
 
 In [8]: getattr(p, 'name')
 ---------------------------------------------------------------------------
 AttributeError                            Traceback (most recent call last)
 <ipython-input-8-ee5bfa7ae925> in <module>
 ----> 1 getattr(p, 'name')
 
 AttributeError: 'Person' object has no attribute 'name'

5、检查对象是否可被调用:callable()

s1 = 'asdfg'

def func():
    pass

print(callable(s1))  # False
print(callable(func))  # True