Python基础——第八章 第二部分 内置函数

常见的内置函数

1、查看内置函数

dir(__builtins__)查看所有的常见内置函数

print(dir(__builtins__))
'''执行结果

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 
'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 
'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 
'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError',
 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 
'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 
'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 
'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 

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

2、简单内置函数

2.1、常见函数

    len    求长度

    min    求最小值

    max    求最大值

    sorted    排序

    reversed    反向

    sum    求和

a=[1,2,3,11,6,7,4,5,8,9]

print(len(a))      '''执行结果:10'''
print(min(a))      '''执行结果:1'''
print(max(a))      '''执行结果:11'''
print(sorted(a))      '''执行结果:[1, 2, 3, 4, 5, 6, 7, 8, 9, 11]'''
print(list(reversed(a)))    '''执行结果:[9, 8, 5, 4, 7, 6, 11, 3, 2, 1]'''
print(sum(a))      '''执行结果:56'''

2.2、进制转换函数

    bin    转换为二进制

    oct    转换为八进制

    hex    转换为十六进制

    ord    字符转ASCII码

    chr    ASCII码转字符

print(bin(2))   '''执行结果:0b10'''
print(oct(8))   '''执行结果:0o10'''
print(hex(16))  '''执行结果:0x10'''
print(ord('a')) '''执行结果:97'''
print(chr(65))  '''执行结果:A'''

2.3、高级内置函数

enumerate:返回一个可以枚举的对象

lb= ['a','b','c']


print(enumerate(lb))         '''执行结果:<enumerate object at 0x0000000002FDBCA8>'''  
print(list(enumerate(lb)))   '''执行结果:[(0, 'a'), (1, 'b'), (2, 'c')]'''  
print(dict(enumerate(lb)))   '''执行结果:{0: 'a', 1: 'b', 2: 'c'}'''  

eval:1、取出字符串中的内容

          2、将字符串str当成有效的表达式来求值并返回计算结果

a='1+2+3'
b='1'+'2'+'3'

print(eval(a))
print(eval(b))

exec:执行字符串编译过的字符串

a=1
b=2
exec('tt = a + b')
print(tt)          '''执行结果:3'''

filter:过滤器,筛选器

def func(x):
    return x>10
li=[1,111,23,54,4,8,1,1,745,2,4,22,65,2]  #列表
tu=(1,111,23,54,4,8,1,1,745,2,4,22,65,2)  #元组

print(list(filter(func,li)))  '''执行结果:[111, 23, 54, 745, 22, 65]'''
print(list(filter(func,tu)))  '''执行结果:[111, 23, 54, 745, 22, 65]'''

map():对于参数iteralble中的每个元素都应用function函数,并将结果作为列表返回

def func(x):
    return x>10
li=[1,111,23,54,4,8,1,1,745,2,4,22,65,2]  #列表
tu=(1,111,23,54,4,8,1,1,745,2,4,22,65,2)  #元组

print(list(map(func,li)))
print(list(map(func,tu)))
'''执行结果:[False, True, True, True, False, False, False, False, True, False, False, True, True, False]'''




def func(x):
    return x*10
li=[1,111,23,54,4,8,1,1,745,2,4,22,65,2]  #列表
tu=(1,111,23,54,4,8,1,1,745,2,4,22,65,2)  #元组

print(list(map(func,li)))
print(list(map(func,tu)))
'''执行结果:[10, 1110, 230, 540, 40, 80, 10, 10, 7450, 20, 40, 220, 650, 20]'''

zip:将对象逐一配对

l1=[1,2,3,4,5]
l2=['a','b','c']

print(list(zip(l1,l2)))  '''执行结果:[(1, 'a'), (2, 'b'), (3, 'c')]'''
print(dict(zip(l2,l1)))  '''执行结果:{'a': 1, 'b': 2, 'c': 3}'''

猜你喜欢

转载自blog.csdn.net/weixin_44435602/article/details/114933429