• 内置函数,现在应该掌握的


    1.abs(n):n的绝对值

    a = 12
    b = -13
    c = a + abs(b)
    print(c)#25

    2.all(iterable):集合中有一个为假,则返回值为假,全部为真才为真,参数只能有一个

    a = [12, 17, 36]
    b = ['123', '', 5]
    e = []
    c = all(a)
    d = all(b)
    e = all(e)
    print(c)#True
    print(d)#False
    print(e)#True,此为例外,当为空列表的时候返回值为真

    3.any(iterable):集合中的元素有一个为真的时候为真

    a = {}
    b = ['123', '', 5]
    e = (0,'')
    c = any(a)
    d = any(b)
    e = any(e)
    print(c)#False若为空串返回为False
    print(d)#True
    print(e)#False

    4.bin(n):将整数n转换为二进制字符串

    a = bin(8)
    b = bin(21)
    print(a)#0b1000,0b代表2进制
    print(b)#0b10101

     5.bool([x]):转为布尔值

    a = bool(18)
    print(a)#True
    b = bool('')
    print(b)#False

    6.bytes([source[, encoding[, errors]]]):转换为字节,返回数组不可修改

    a = bytes(3)  # 当source参数为整数时,返回这个整数所指定长度的空字节数组,且不能为负值
    print(a, len(a)) # b'x00x00x00' 3
    b = bytes('人民', encoding='utf-8') # 当source参数为字符串时,encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组
    print(b, len(b)) # b'xe4xbaxbaxe6xb0x91' 6
    f = '中国'.encode('utf-8')
    print(f, len(f)) # b'xe4xb8xadxe5x9bxbd' 6
    c = bytes()
    print(c, len(c)) # b'' 0,当3个参数都不传的时候,返回长度为0的字节数组
    e = bytes([12, 14, 16]) # 当source参数是一个可迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里
    print(e, len(e)) # b'x0cx0ex10' 3
    m = bytes(range(1,16))
    print(m, len(m)) # b'x01x02x03x04x05x06x07x08 x0bx0c x0ex0f' 15

     7.chr(i, /):Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

    print(chr(98))  # b

    8.dict(object):创建 字典

    a = {'name': 'tom', 'age': 22, 12: 22}  # 直接生成字典
    print(a) # {'name': 'tom', 'age': 22, 12: 22}
    b = dict(name='tom', age=22, ) # 注意:key键不能用引号,不能写'name'='tom',同时key也不能为一个表达式12=13或者11='as'
    print(b) # {'name': 'tom', 'age': 22}
    f = dict([('name', 'age'), ('tom', 22), ('address', 'beijing'), (12, 13)]) # 使用dict()时必须是元素是元组的列表才可以使用
    print(f) # {'name': 'age', 'tom': 22, 'address': 'beijing', 12: 13}
    d = dict.fromkeys(range(1, 5), (
    'tom')) # 会生成一个value值相等的字典,注意:fromkeys()里面可以跟两个参数,第二个不写时默认是None,不能多增加字典的值,key可以是可迭代的d = dict.fromkeys(range(1,5), ('tom'))结果为{1: 'tom', 2: 'tom', 3: 'tom', 4: 'tom'}
    print(d) # {'name': 'tom', 'age': 'tom'}

    9.dir(object):查看对象的属性,包括对象类型方法

    a = dir('c')  # 查看字符串的属性
    print(a)
    b = dir(chr)  # 查看chr的属性
    print(b)
    c = dir({})  # 查看字典的属性
    print(c)

    10.divmod(x, y, /):返回一个元组,包含x/y的商和余数

    print(divmod(20, 6))  # (3, 2),可用于网站分页

    11.enumerate(iterable[, start]) -> iterator for index, value of iterable:为可迭代的值增加索引,第二个参数为起始索引

    for i in enumerate('abcde',10):
        print(i)
    
    (10, 'a')
    (11, 'b')
    (12, 'c')
    (13, 'd')
    (14, 'e')

    12.eval():用来执行字符串表达式并返回表达式的值

    print(eval('6*6'))  # 36
    n = 18
    print(eval('n+12')) # 30
    print(eval('divmod(50,25)')) # (2, 0)

    13.filter(function or None, iterable) --> filter object:用函数过滤序列,返回一个符合条件的新序列

    def abc(x):  # 定义函数
    return x % 2 == 0 # 偶数返回真


    print(list(filter(abc, range(10)))) # [0, 2, 4, 6, 8]需要用list将filter的值转成列表

    14.float(x) -> floating point number:将整形和字符串转为浮点数

    print(float(18))  # 18.0
    print(float('123'))  # 123.0

    15.globals():返回全局变量的字典

    a = []
    b = 'abc'
    c = 123  # globals 函数返回一个全局变量的字典,包括所有导入的变量。
    print(
        globals())  # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x04C3E990>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'E:/py/hanshu.py', '__cached__': None, 'a': [], 'b': 'abc', 'c': 123}

    16.help:帮助

    17.hex(number, /):返回16进制,以字符串形式表示

    print(hex(17))  # 0x11
    print(hex(eval('19')))  # 0x13

    18.id(obj, /):返回对象的ID地址

    a = 5
    print(id(a))  # 1437456240
    b = ['a', 'b', 'c']
    print(id(b))  # 80200528

    19.input():输入

    20.int(x, base=10) -> integer:字符串或者数字转化成整型,base默认为10进制

    print(int(3.55))  # 3
    print(int('100', base=2))  # 4

    21.isinstance(obj, class_or_tuple, /):判断对象是否是一个已知的类或者这些类的元组

    print(isinstance([12, 24], tuple))  # False
    print(isinstance([12, 24], (tuple, dict, list)))  # True

    22.len(obj, /):返回对象的长度或者个数

    print(len('abc'))  # 3
    print(len({12: 22, 13: 5, 'abc': 6}))  # 3

    23.list(object):创建列表,参数需为元组

    a = [12, 13]
    print(a)  # [12, 13]
    b = (12, 'aabc', 58)
    print(list(b))  # [12, 'aabc', 58]

     24.locals():返回一个名字/值对的字典,所有的局部变量

    def abc(a, b):
    x = 9 # 'x': 9
    y = 'xxx' # y': 'xxx'
    for i in range(0, 5): # 循环取得是最后一个值
    k = i # 'k': 4, 'i': 4
    m = 18 # 'm': 18
    print(locals()) # {'m': 18, 'k': 4, 'i': 4, 'y': 'xxx', 'x': 9, 'b': 7, 'a': 8}


    W = 5 # 全局变量,所以不输出
    abc(8, 7) # 'b': 7, 'a': 8

    25. map(func, *iterables) --> map object:它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回,map()函数不改变原有的 list,而是返回一个新的 list。第一个参数接受一个函数名,后面的参数接受一个或多个可迭代的序列,返回的是一个集合

    def abc(x):  # 定义函数
        return x ** 2  # 平方操作
    
    
    print(list(map(abc, [1, 2, 3])))  # [1, 4, 9]需要用list将map的值转成列表

    def abc(x,y):  # 定义函数
    return x+y # 多个项目相加


    print(list(map(abc, [1, 2, 3], [2, 3, 4]))) # [3, 5, 7]需要用list将map的值转成列表

    a = ['adam', 'LISA', 'barT']


    def abc(x):
    return x.lower().title()


    print(a) # ['adam', 'LISA', 'barT']
    print(list(map(abc, a))) # ['Adam', 'Lisa', 'Bart']

    26.max(iterable, *[, default=obj, key=func]) -> value  max(arg1, arg2, *args, *[, key=func]) -> value:求最大值

    print(max(12, 13, 2 * 6, eval('3*6')))  # 18
    c = max([1, 2, 3], [0, 0, 10], [2, 3, 9], [2, 3, 5])
    print(c, type(c))  # [2, 3, 9] <class 'list'>
    b = max((1, 2), (1, 2.1))
    print(b, type(b))  # (1, 2.1) <class 'tuple'>
    
    
    def abc(x):  # 定义函数
        return abs(x)  # 求绝对值
    
    
    print(max([9, -18, 0, 27, -36], key=abc))  # -36根据key函数找到最大值

    27.min(iterable, *[, default=obj, key=func]) -> value  min(arg1, arg2, *args, *[, key=func]) -> value:求最小值(等同max)

    28. oct(number, /):八进制

    print(oct(10))  # 0o12

    29.open:打开文件,单说

    30.ord():函数是chr()函数(对于8位的ASCII字符串)或unichr()函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的ASCII数值,或者Unicode数值,如果所给的Unicode字符超出了你的Python定义范围,则会引发一个TypeError的异常

    print(ord('A'))  # 65
    print(ord('2'))  # 50

    31.pow(x, y, z=None, /)Equivalent to x**y (with two arguments) or x**y % z (with three arguments):x的y次幂,三个参数代表x的y次幂 再除以z的余数

    print(pow(2, 3))  # 8
    print(pow(3, 3, 5))  # 2

    32.range(object):range(stop) -> range object  range(start, stop[, step]) -> range object:产生一个序列,第一个参数起始值默认从0开始,第二个终止值,第三个步幅默认1

    print(range(10))  # range(0, 10)迭代的时候会输出
    for i in range(2, 10, 3):
        print(i)  # 2,5,8

    33. round(number[, ndigits]) -> number:四舍五入,第二个参数控制小数位

    print(round(1.777))  # 2
    print(round(1.777, 2))  # 1.78
    print(round(1 / 2))  # 0
    print(round(1.555, 2))  # 1.55
    '''官方文档写了,round(number[, ndigits]) values are rounded to the closest multiple of 10 to the power minus ndigits; 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). 
    
    就是说round(1/2)取离它最近的整数,如果2个数(0和1)离它一样近,则取偶数(the even choice)。
    
    因此round(1.5)=2, round(2.5)=2, round(3.5)=4, round(4.5)=4。'''

    34.sorted(iterable, /, *, key=None, reverse=False)  Return a new list containing all items from the iterable in ascending order.排序

    a = ['Smooth', 'is', 'fast', 'Fast', 'is', 'smooth', '1', '12']
    print(sorted(a))  # ['Fast', 'Smooth', 'fast', 'is', 'is', 'smooth']字符串和数字不能放到一起
    print(sorted(a, reverse=True))  # ['smooth', 'is', 'is', 'fast', 'Smooth', 'Fast', '12', '1']reverse为 True则倒序
    
    
    def abc(x):
        return len(x)  # 定义字符串长度
    
    
    print(sorted(a, key=abc))  # ['1', 'is', 'is', '12', 'fast', 'Fast', 'Smooth', 'smooth']按字符串的长度作为关键字排序

    35.str(object)str(object='') -> str  str(bytes_or_buffer[, encoding[, errors]]) -> str:转换为字符串

    a = 1
    b = 'abc'
    c = str(a) + b
    print(c)  # 1abc

    a = bytes('abc', encoding='utf-8')
    print(a, type(a)) # b'abc' <class 'bytes'>
    b = str(a)
    print(b, type(b)) # b'abc' <class 'str'>
    b = str(a, encoding='utf-8')
    print(b, type(b)) # abc <class 'str'>
     

    36.sum(iterable, start=0, /)  Return the sum of a 'start' value (default: 0) plus an iterable of numbers:累加,只能是数字,第一个参数必须是可迭代的,第二个是起始值默认0

    print(sum([1, 2, 3]))  # 6
    print(sum(range(2, 6, 2), 4))  # 10

    37.tuple() -> empty tuple  tuple(iterable) -> tuple initialized from iterable's items:创建元组

    print(tuple(range(5)))#(0, 1, 2, 3, 4)
    print(tuple([18,22]))#(18, 22)

    38.type:查看类型

    print(type('a'))  # <class 'str'>
    b = {12, 13}
    print(type(b))  # <class 'set'>
  • 相关阅读:
    关于iterator的一点疑惑
    shuffle()方法
    List简单使用笔记
    Arrays.asList()
    多项式ADT(数组存储多项式系数和指数)笔记
    《数据结构与算法分析C语言描述》源码网盘分享
    C语言实现链表
    typedef的用法
    #ifndef的用法
    mysql创建数据库和数据表模板
  • 原文地址:https://www.cnblogs.com/xusuns/p/8258420.html
Copyright © 2020-2023  润新知