内置函数 built-in
1. 数字相关
1. 进制转换
print ( bin ( 2 ) )
print ( oct ( 22 ) )
print ( hex ( 22 ) )
2. 数据类型
bool :布尔类型(True, False)int :整型float :浮点型complex :复数
3. 数学运算
print ( ads( - 22 ) )
print ( divmod ( 22 , 3 ) )
print ( round ( 32.2345 , 2 ) )
pow(a, b,z=none) :求a的b次幂, 如果有三个参数. 则求完次幂后对第三个数取余
print ( pow ( 2 , 3 ) )
print ( pow ( 2 , 3 , 3 ) )
print ( sum ( [ 1 , 2 , 3 , 5 ] ) )
print ( min ( [ 1 , 2 , 3 , 5 ] ) )
print ( max ( [ 1 , 2 , 3 , 5 ] ) )
eval() :执行字符串类型的代码. 并返回最终结果
s = input ( "请输入a+b:" )
print ( eval ( s) )
2. 数据结构相关
1. 序列
print ( list ( ( 1 , 2 , 3 ) ) )
print ( tuple ( [ 1 , 2 , 3 ] ) )
reversed() :将一个序列翻转, 返回翻转序列的迭代器
list1 = [ 2 , 3 , 4 , 6 ]
list2 = list ( reversed ( list1) )
print ( list2)
list1 = [ 2 , 3 , 4 , 6 ]
s = slice ( 1 , 3 , 1 )
print ( list1[ s] )
2. 数据
print ( type ( str ( 22 ) ) )
format() :与具体数据相关, 用于计算各种小数, 精算等.
str1 = "hello world!"
print ( format ( str1, "^20" ) )
print ( format ( str1, "<20" ) )
print ( format ( str1, ">20" ) )
print ( format ( 2 , 'b' ) )
print ( format ( 98 , 'c' ) )
print ( format ( 22 , 'd' ) )
print ( format ( 22 , 'o' ) )
print ( format ( 10 , 'x' ) )
print ( format ( 10 , 'X' ) )
print ( format ( 22 , 'n' ) )
print ( format ( 22 ) )
print ( format ( 123456789 , 'e' ) )
print ( format ( 123456789 , '0.2e' ) )
print ( format ( 123456789 , '0.2E' ) )
print ( format ( 1.23456789 , 'f' ) )
print ( format ( 1.23456789 , '0.2f' ) )
print ( format ( 1.23456789 , '0.10f' ) )
print ( format ( 1.23456789e+3 , 'F' ) )
bs = bytes ( "学习python" , encoding= "utf-8" )
print ( bs)
bytearray() :返回一个新字节数组. 这个数字的元素是可变的, 并且每个元素的值得范围是[0, 256]
byt = bytearray ( "nancy" , encoding= "utf-8" )
print ( ret)
print ( ret[ 1 ] )
byt[ 1 ] = 98
print ( byt)
print ( ord ( 'b' ) )
print ( chr ( 98 ) )
ascii() :是ascii码中的返回该值 不是就返回u
print ( ascii ( 'hello' ) )
str1 = "今天\t加了%s小时\n班" % 3
print ( str1)
print ( repr ( str1) )
3. 数据集合
dict : 创建一个字典set : 创建一个集合
frozenset() 创建一个冻结的集合,冻结的集合不能进行添加和删除操作。
s1 = set ( [ 1 , 2 , 3 , 4 ] )
print ( s1)
s1. add( 5 )
print ( s1)
s2 = frozenset ( [ 1 , 2 , 3 ] )
print ( s2)
s2. add( 4 )
print ( s2)
print ( len ( [ 1 , 2 , 3 , 4 ] ) )
sorted() :对可迭代对象进行排序操作
sorted**(iterable, key =itemgetter, reverse =bool )**
iterable:可迭代对象 key**=**itemgetter:排序规则 reverse**=**bool:是否倒序,True为倒序,False为正序,默认为正序
list1 = [ 2 , 1 , 45 , 3 , 1 , 0 , - 4 , 20 , 33 ]
list2 = sorted ( list1)
print ( list2)
list3 = sorted ( list1, reverse= True )
print ( list3)
list4 = [ 'aa' , 'b' , 'adbc' , 'ff' , 'hello world' ]
def func ( s) :
return len ( s)
list5 = sorted ( list4, key= func)
print ( list5)
list6 = [ 'aa' , 'b' , 'adbc' , 'ff' , 'hello world' ]
for index, i in enumerate ( list6) :
print ( index, i)
**all() **:可迭代对象中全部是True, 结果才是True
print ( all ( [ 1 , 'he' , 'll' , 'o' ] ) )
print ( all ( [ 1 , 'he' , 'll' , 'o' , 1 > 2 ] ) )
any() :可迭代对象中有一个是True, 结果就是True
print ( any ( [ False , 0 , 0 , 1 > 2 , 2 ] ) )
zip() : 函数用于将可迭代的对象作为参数, 将对象中对应的元素打包成一个元组, 然后返回由这些元组组成的列表. 如果各个迭代器的元素个数不一致, 则返回列表长度与最短 的对象相同
list7 = [ 1 , 2 , 3 , 4 ]
list8 = [ 'a' , 'b' , 'c' , 'd' ]
list9 = [ 'hello' , 'world' ]
for i in zip ( list7, list8, list9) :
print ( i)
fiter(function. Iterable) : 用来筛选的函数. 在filter中会自动的把iterable中的元素传递给function. 然后根据function返回的True或者False来判断是否保留留此项数据 , Iterable: 可迭代对象
list10 = [ 'aa.log' , 'bb.log' , 'cc' ]
print ( filter ( lambda x: x. endswith( '.log' ) , list10) )
print ( list ( filter ( lambda x: x. endswith( '.log' ) , list10) ) )
**map(function, iterable) **:可以对可迭代对象中的每一个元素进行映射. 分别去执行 function
list11 = [ 1 , 2 , 3 ]
def func ( i) :
return i + 10
print ( map ( func, list11) )
print ( list ( map ( func, list11) ) )
3. 作用域相关
**locals() **:返回当前作用域中的名字 **globals() **:返回全局作用域中的名字
str1 = 'roy'
def func ( ) :
my_syr = 'nancy'
print ( locals ( ) )
print ( globals ( ) )
func( )
"""
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fc502071fd0>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
'__file__': '/Users/roy/Documents/my_code/test_a/built-in.py', '__cached__': None,
'str1': 'roy', 'func': <function func at 0x7fc5020ea680>}
"""
4. 输入输出
5. 帮助
print ( help ( input ) )
"""
Help on built-in function input in module builtins:
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
None
"""
6. 迭代器&生成器
range() : 生成数据**next() : **迭代器向下执行一次, 内部实际使⽤用了__ next__()⽅方法返回迭代器的下一个项目 iter() : 获取迭代器, 内部实际使用的是__ iter__()⽅方法来获取迭代器
for i in range ( 1 , 4 ) :
print ( i)
list11 = [ 2 , 4 , 6 , 8 , 10 ]
iter1 = iter ( list11)
print ( iter1. __next__( ) )
print ( next ( iter1) )
print ( next ( iter1) )
print ( next ( iter1) )
7. 内存相关
hash() : 获取到对象的哈希值(int, str, bool, tuple)
hash算法
目的是唯一性 dict 查找效率非常高, 因为dict的key以hash值作为索引存储。hash表用空间换的时间,比较耗费内存
print ( hash ( 'nancy' ) )
8. 文件操作相关
open() : 用于打开一个文件, 创建一个文件句柄
f = open ( 'test_file' , mode= 'r' , encoding= 'utf-8' )
print ( f)
print ( f. read( ) )
f. close( )
**with open(path, mode, encoding) as f:**也是打开文件,不用手动关闭,程序结束后自动释放资源
9. 调用相关
callable() : 用于检查一个对象是否是可调用的. 如果返回True, object有可能调用失败, 但如果返回False. 那调用绝对不会成功
t = 'nancy'
print ( callable ( t) )
def func ( ) :
print ( "hello nancy" )
print ( callable ( func) )
func( )
10. 查看内置属性
dir() : 查看对象的内置属性, 访问的是对象中的__dir__()方法,返回值为
print ( dir ( list ) )
"""
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__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']
"""
汇总
abs ( ) all ( ) any ( ) ascii ( )
bin ( ) bool ( ) bytearray ( ) bytes ( )
callable ( ) chr ( ) classmethod ( ) compile ( ) complex ( )
dict ( ) dir ( ) delattr ( ) divmod ( )
enumerate ( ) eval ( ) exec ( )
format ( ) frozenset ( ) filter ( ) float ( )
globals ( ) getattr ( )
hasattr ( ) hash ( ) help ( ) hex ( )
id ( ) input ( ) int ( ) issubclass ( ) iter ( ) isinstance ( )
len ( ) list ( ) locals ( )
map ( ) max ( ) memoryview ( ) min ( )
next ( )
object ( ) oct ( ) open ( ) ord ( )
pow ( ) print ( ) property ( )
range ( ) repr ( ) reversed ( ) round ( )
set ( ) setattr ( ) slice ( ) staticmethod ( ) str ( ) sum ( ) super ( ) sorted ( )
type ( ) tuple ( )
vars ( )
zip ( )