zoukankan      html  css  js  c++  java
  • python内置函数

    python内置函数

    查看python的内置函数

    >>> 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']
    

    作用域相关 ★★★★★

    locals() 函数会以字典的类型返回当前位置的全部局部变量。若在最外面,与globals()相同。

    globals() 函数以字典的类型返回全部全局变量。

    a = 1
    b = 2
    def f1():
        c = 1
        print('inner locals>>>>', locals())
    f1()
    print('globals>>>>', globals())
    print('outer locals>>>>', locals())
    
    print(globals() == locals())  # 若在最外面,与globals()相同。结果为True
    '''
    inner locals>>>> {'c': 1}
    globals>>>> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000262523AC1D0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:\oldboy_project\test3.py', '__cached__': None, 'a': 1, 'b': 2, 'f1': <function f1 at 0x00000262522A2E18>}
    outer 
    locals >>>> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000262523AC1D0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:\oldboy_project\test3.py', '__cached__': None, 'a': 1, 'b': 2, 'f1': <function f1 at 0x00000262522A2E18>}
    True
    '''
    

    其他相关

    字符串类型代码的执行 eval,exec,complie,不建议使用★★★☆☆

    # print(eval('x')) # not defined
    x = 1
    print(eval('x + 3')) # 4
    print(exec('x + 3')) # None
    

    输入输出相关 input,print ★★★★★

      input:函数接受一个标准输入数据,返回为 string 类型。参数默认为None,若给了字符串,会出现提示内容。

      print:打印输出。

    print(*args, sep=' ', end='
    ', file=sys.stdout, flush=False)
    sep 是args每个参数显示的间隔。
    end 是最后以什么结束。
    file 接收文件句柄,可以赋值给一个文本文件。
    flush 立即把内容输出到流文件,不作缓存
    
    with open('print.txt', mode='w', encoding='utf-8') as f:
        print('hello world!I am learning python.', file=f)
    # 命令行中没有显示结果,而新建了一个“print.txt"文件,里面有所写的内容。
    
    print(1, 2, 3, sep='|') # 1|2|3
    

    内存相关 hash id ★★★☆☆

    • hash:获取一个对象(可哈希对象:int,str,Bool,tuple)的哈希值。
      hash一般会得到一个长度为18的数字,
      若是数值长度超过18会得到一个长度18的数字。
      长度小于18会是它原来的数值。
    >>> a = 100
    >>> b = '100'
    >>> c = True
    >>> tu = (1, 2)
    >>> hash(a)    #数字还是它所显示的值。
    100
    >>> hash(b)
    5677959494014640638
    >>> hash(c)
    1
    >>> hash(tu)
    3713081631934410656
    
    • id: 获取该对象的内存地址。

    文件操作相关

    open() ★★★★★

    函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。

    模块相关__import__  ★★★☆☆

     __import__:函数用于动态加载类和函数 。

    帮助 help:函数用于查看函数或模块用途的详细说明。 ★★☆☆☆

    name = 'alex'
    print(help(str))
    

      

    调用相关

      callable:函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功。 ★★★☆☆

    >>> def f1():
    ...     print('a')
    ...
    >>> callable(f1)
    True
    >>> name = 'python'
    >>> callable(name)
    False
    

    查看内置属性 ★★★☆☆

      dir:函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。
    如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。

    >>> s = 'abc'
    >>> dir(s)
    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
    

    迭代生成器相关

    range:函数可创建一个整数对象,一般用在 for 循环中。

     python2x: range(3) ---> [0,1,2] 列表
               xrange(3) ---> 一个生成器
     python3x: range(3) ---> range(0,3) 可迭代对象
    

    next:内部实际使用了__next__方法,返回迭代器的下一个项目。

    # 首先获得Iterator对象:
    it = iter([1, 2, 3, 4, 5])
    # 循环:
    while True:
        try:
            # 获得下一个值:
            x = next(it)
            print(x)
        except StopIteration:
            # 遇到StopIteration就退出循环
            break
    

    iter:函数用来生成迭代器(讲一个可迭代对象,生成迭代器)。

    from collections import Iterable
    from collections import Iterator
    l = [1,2,3]
    print(isinstance(l,Iterable))  # True
    print(isinstance(l,Iterator))  # False
    
    l1 = iter(l)
    print(isinstance(l1,Iterable))  # True
    print(isinstance(l1,Iterator))  # True
    
    

    我是位置1

    基础数据类型相关

    数字相关

    数据类型(4)

    bool :用于将给定参数转换为布尔类型,如果没有参数,返回 False。
    >>> bool()
    False
    >>> bool(0)==bool('')==bool([])==bool(tuple())==bool(set())==bool({})
    True
    
    int:函数用于将一个字符串或数字转换为整型。
    >>> int('10', base=2)  #二进制转十进制
    2
    >>> int('10', base=8)  #八进制转十进制
    8
    >>> int('1e', base=16) #十六进制转十进制
    30
    >>> int(3.8)   # 浮点数强制转整形
    3
    >>> int()   # 默认为0
    0
    
    
    float:函数用于将整数和字符串转换成浮点数。
    >>> float()
    0.0
    >>> float('+1.23')
    1.23
    >>> float('   -12345
    ')
    -12345.0
    >>> float('1e-003')
    0.001
    >>> float('+1E6')
    1000000.0
    >>> float('-Infinity')
    -inf
    
    
    complex:

    函数用于创建一个值为 real + imag * j 的复数或者转化一个字符串或数为复数。如果第一个参数为字符串,则不需要指定第二个参数。

    进制转换(3)

    bin:将十进制转换成二进制并返回。
    >>> bin(3)
    '0b11'
    >>> bin(-10)
    '-0b1010'
    
    oct:将十进制转化成八进制字符串并返回。
    >>> oct(8)
    '0o10'
    >>> oct(-56)
    '-0o70'
    
    hex:将十进制转化成十六进制字符串并返回。
    >>> hex(255)
    '0xff'
    >>> hex(-42)
    '-0x2a'
    

    数学运算(7):

    abs:函数返回数字的绝对值。
    >>> abs(-20)
    20
    >>> abs(-28.33)
    28.33
    
    divmod:计算除数与被除数的结果,返回一个包含商和余数的元组(a // b, a % b),可以用到页码的计算。
    >>> divmod(2.4, 1.1)
    (2.0, 0.19999999999999973)
    >>> divmod(33, 15)
    (2, 3)
    >>>
    
    round:保留浮点数的小数位数,默认保留整数。
    >>> round(0.5)
    0
    >>> round(1.5)
    2
    #  if two multiples are equally close, rounding is done toward the even choice # (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2). 
    
    pow:求xy次幂。(三个参数为xy的结果对z取余)
    >>> pow(3, -2, 3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: pow() 2nd argument cannot be negative when 3rd argument specified
    >>> pow(3, 2, 7)
    2
    
    sum:对可迭代对象进行求和计算(可设置初始值)。
    >>> sum([1,2,3,4], 10)
    20
    
    min:返回可迭代对象的最小值(可加key,key为函数名,通过函数的规则,返回最小值)。 key可以跟lambda函数用。
    >>> min([-1, 3, 4, 9, -10])
    -10
    >>> min([-1, 3, 4, 9, -10], key=abs)
    -1
    
    max:返回可迭代对象的最大值(可加key,key为函数名,通过函数的规则,返回最大值)。key可以跟lambda函数用。
    >>> max([-1, 3, 4, 9, -10])
    9
    >>> max([-1, 3, 4, 9, -10], key=abs)
    -10
    

    和数据结构相关

    列表和元祖(2)

    list:将一个可迭代对象转化成列表(如果是字典,默认将key作为列表的元素)。
    >>> list({'a':1, 'b':3})
    ['a', 'b']
    
    tuple:将一个可迭代对象转化成元祖(如果是字典,默认将key作为元祖的元素)。

    相关内置函数(2)

    reversed:将一个序列翻转,并返回此翻转序列的迭代器。
    >>> reversed([3,1,6,4,9])   # Return a reverse iterator. 
    <list_reverseiterator object at 0x000001B2B4258E80> 
    >>> list(reversed([3,1,6,4,9]))
    [9, 4, 6, 1, 3]
    
    slice:构造一个切片对象,用于列表的切片。
    >>> li = ['a','b','c','d','e','f','g']
    >>> li[slice(3)]
    ['a', 'b', 'c']
    >>> li[slice(1, 3)]
    ['b', 'c']
    >>> li[slice(1, None, 2)]
    ['b', 'd', 'f']
    >>> li[slice(1, None, 1)]
    ['b', 'c', 'd', 'e', 'f', 'g']
    

    字符串相关(9)

    数据集合(3)

    相关内置函数(8)

    匿名函数

  • 相关阅读:
    leetcode 268. Missing Number
    DBSCAN
    python二维数组初始化
    leetcode 661. Image Smoother
    leetcode 599. Minimum Index Sum of Two Lists
    Python中的sort() key含义
    leetcode 447. Number of Boomerangs
    leetcode 697. Degree of an Array
    滴滴快车奖励政策,高峰奖励,翻倍奖励,按成交率,指派单数分级(1月3日)
    北京Uber优步司机奖励政策(1月2日)
  • 原文地址:https://www.cnblogs.com/lanhoo/p/9514330.html
Copyright © 2011-2022 走看看