zoukankan      html  css  js  c++  java
  • [Python笔记]第四篇:内置函数

    本篇主要内容:内置函数

     函数

    参考:https://docs.python.org/3.5/library/functions.html

    内置函数列表

    一、数学运算类


    abs(x)求绝对值
    >>> abs(-3306)
    3306

    complex([real[, imag]])创建一个复数
    >>> complex(10)
    (10+0j)
    >>>

    divmod(a, b)分别取商和余数注意:整型、浮点型都可以
    >>> divmod(10,3)
    (3, 1)

    float([x])将一个字符串或数转换为浮点数。如果无参数将返回0.0
    >>> float("3.2")
    3.2

    int([x[, base]])将一个字符转换为int类型,base表示进制
    >>> int("1000000", base=2)
    64

    pow(x, y[, z])返回x的y次幂
    >>> pow(8,2,)
    64
    >>> pow(8,2,10) # 8的2次方整除10的余数
    4

    range([start], stop[, step])产生一个序列,默认从0开始
    >>> for i in range(5): #默认输出
    ...     print(i)
    ...
    0
    1
    2
    3
    4
    >>>
    >>> for i in range(1,5): #指定起始值
    ...     print(i)
    ...
    1
    2
    3
    4
    >>>
    >>> for i in range(1,5,2): #指定起始值和步进长度
    ...     print(i)
    ...
    1
    3
    >>>

    round(x[, n])四舍五入
    >>> round(1.1)
    1
    >>> round(1.5)
    2

    sum(iterable[, start])对集合求和
    >>> sum([1,2,3,4,5])
    15

    oct(x)将一个数字转化为8进制
    >>> oct(10)
    '0o12'

    hex(x)将整数x转换为16进制字符串
    >>> hex(26)
    '0x1a'

    chr(i)返回整数i对应的ASCII字符
    >>> chr(65)
    'A'

    bin(x)将整数x转换为二进制字符串
    >>> bin(1024)
    '0b10000000000'

    bool([x])将x转换为Boolean类型
    >>> bool([])    # 空列表
    False
    >>> bool(())    # 空元组
    False
    >>> bool({})    # 空字典
    False
    >>> bool(-1)    
    True
    >>> bool(0)
    False
    >>> bool(1)
    True
    >>>

    二、集合操作类

    format(value [, format_spec]) 格式化输出字符串格式化的参数顺序从0开始,如“I am {0},I like {1}”
    >>> print('We are the {} who say "{}!"'.format('guys', 'Hi'))
    We are the guys who say "Hi!"

    enumerate(sequence [, start = 0]) 返回一个可枚举的对象,该对象的next()方法将返回一个tuple
    t = (1,2,3,4,5,6)
    for i in enumerate(t):  # enumerate() 为可迭代的对象添加序号,默认从0开始
        print(i)
    
    (0, 1)
    (1, 2)
    (2, 3)
    (3, 4)
    (4, 5)
    (5, 6)

    iter(o[, sentinel]) 生成一个对象的迭代器,第二个参数表示分隔符
    >>> s = 'abc'
    >>> it = iter(s)
    >>> it
    <iterator object at 0x00A1DB50>
    >>> next(it)
    'a'
    >>> next(it)
    'b'
    >>> next(it)
    'c'
    >>> next(it)
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
        next(it)
    StopIteration

    max(iterable[, args...][key]) 返回集合中的最大值
    >>> max([11,22,33,44,55])
    55

    min(iterable[, args...][key]) 返回集合中的最小值
    >>> min([11,22,33,44,55])
    11

    dict([arg]) 创建数据字典
    >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
    {'sape': 4139, 'jack': 4098, 'guido': 4127}

    list([iterable]) 将一个集合类转换为另外一个集合类
    >>> t = (11,22,33,44,55)
    >>> type(t)
    <class 'tuple'>
    >>> li = list(t)
    >>> li
    [11, 22, 33, 44, 55]
    >>> type(li)
    <class 'list'>
    >>>

    set() set对象实例化
    >>> a = set('abracadabra')
    >>> b = set('alacazam')
    >>> a                                  # a中不重复的元素
    {'a', 'r', 'b', 'c', 'd'}
    >>> a - b                              # a中存在b没有的
    {'r', 'd', 'b'}
    >>> a | b                              # a和b全部的元素
    {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
    >>> a & b                              # a中存在且b中存在
    {'a', 'c'}
    >>> a ^ b                              # 非(a中存在且b中存在)
    {'r', 'd', 'b', 'm', 'z', 'l'}

    frozenset([iterable]) 产生一个不可变的set
    >>> se = set("a,b,c,d,e,f")
    >>> se
    {'a', 'd', 'f', 'b', 'c', 'e', ','}
    >>> fse = frozenset(se)
    >>> fse
    frozenset({'b', 'c', 'e', 'd', ',', 'a', 'f'})
    >>> fse
    frozenset({'b', 'c', 'e', 'd', ',', 'a', 'f'})
    >>>

    str([object]) 转换为string类型
    >>> s = str("abc123")
    >>> s
    'abc123'
    >>> type(s)
    <class 'str'>

    sorted(iterable[, cmp[, key[, reverse]]]) 队集合排序
    >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
    >>> for f in sorted(set(basket)):
    ...     print(f)
    ...
    apple
    banana
    orange
    pear

    tuple([iterable]) 生成一个tuple类型
    >>> li = ["Hello","World"]
    >>> li
    ['Hello', 'World']
    >>> tuple(li)
    ('Hello', 'World')
    >>> t = tuple(li)
    >>> t
    ('Hello', 'World')
    >>> type(t)
    <class 'tuple'>
    >>>
     

    三、逻辑判断类

    all(iterable) 集合中的元素都为真的时候为真;特别的,若为空串返回为True
    >>> all([11,22,-1])
    True
    >>> all([11,22,0])
    False
    >>> all([11,22,[]])
    False
    >>> all([11,22,{}])
    False

    any(iterable) 集合中的元素有一个为真的时候为真;特别的,若为空串返回为False
    >>> any([0,{},[],1])
    True

    四、反射


    eval(expression [, globals [, locals]])   计算表达式expression的值
    >>> eval("2 + 3 * 5 + 1 - 2")
    16
    >>>
    exec() 执行一个存储在字符串或者文件中的python语句
    >>> exec 'print "Hello World"'
    Hello World

    filter(function, iterable) 构造一个序列,等价于[ item for item in iterable if function(item)]
    参数function:返回值为True或False的函数,可以为None
    参数iterable:序列或可迭代对象
    # filter函数
    def f1(x):
        if x > 22:
            return True
        else:
            return False
    ret = filter(f1, [11,22,33,44])
    for i in ret:
        print(i)
    
    33
    44

    getattr(object, name [, defalut]) 获取一个类的属性

    globals() 返回一个描述当前全局符号表的字典

    hasattr(object, name) 判断对象object是否包含名为name的特性

    hash(object) 如果对象object为哈希表类型,返回对象object的哈希值

    id(object) 返回对象的唯一标识
    >>> s = "Hello"
    >>> id(s)
    7222024

    isinstance(object, classinfo) 判断object是否是class的实例
    >>> isinstance(s, str)
    True

    issubclass(class, classinfo) 判断是否是子类

    len(s) 返回集合长度
    >>> len(s)
    5
    locals()  返回当前的变量列表

    map(function, iterable, ...) 	遍历每个元素,执行function操作
    ret = map(lambda y: y > 11, [11, 22, 33])
    for i in ret:
        print(i)
    next(iterator[, default])   迭代出下一个元素
    object()   基类

    reload(module) 	重新加载模块

    setattr(object, name, value)	设置属性值

    repr(object)   将一个对象变幻为可打印的格式

    slice()	
     
    staticmethod	声明静态方法,是个注解

    super(type[, object-or-type]) 	引用父类

    type(object)	返回该object的类型
    >>> s = "Hello"
    >>> type(s)
    <class 'str'>
    vars([object]) 	返回对象的变量

    bytearray([source [, encoding [, errors]]])	返回一个byte数组
    如果source为整数,则返回一个长度为source的初始化数组;
    如果source为字符串,则按照指定的encoding将字符串转换为字节序列;
    如果source为可迭代类型,则元素必须为[0 ,255]中的整数;
    如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray.
    s = "12dffgggggh"
    print(bytearray(s, encoding="utf-8"))
    bytearray(b'12dffgggggh')

    zip([iterable, ...]) 矩阵
    name = ['alex','eric']
    age = [11,22]
    result = zip(name,age)
    for i in result:
        print(i) 
    
    #执行结果
    ('alex', 11)
    ('eric', 22)

    五、IO操作

    open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
    打开文件
    参数filename:文件名称。
    参数mode:'r'(读)、'w'(写)、'a'(追加)。
    # 只读
    f = open("log", "r")
    
    # 只写模式(不可读:文件不存在则创建;存在则清空内容)
    f = open("log", "w")
    
    # 只写模式(不可读,文件不存在则创建,存在则报错)
    f = open("log", "x")
    
    # 追加模式(不存在则创建;存在则只追加内容)
    f = open("log", "s")

    input([prompt]) 获取用户输入
    inp = input("请输入图书编号")
    print	打印函数
    print("请输入图书编号")

    六、其他


    dir 用于按模块名搜索模块定义,它返回一个字符串类型的存储列表

    >>> dir(list) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__' , '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__' , '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__' , '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_e x__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__s izeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'ex tend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
    help 调用内置函数的帮助系统
    >>> help(list)                                                                                                  
    Help on class list in module builtins:
    
    class list(object)
     |  list() -> new empty list
     |  list(iterable) -> new list initialized from iterable's items
    ...
    ...
    ...


  • 相关阅读:
    个人作业week7——前端开发感想总结
    C#【结对编程作业】小学数学习题助手
    【个人作业3】必应词典案例分析
    【个人博客作业II】有关代码规范问题的讨论
    【个人博客作业II】代码复审结果
    【补充】第一次个人项目出现的bug
    《构建之法》阅读反馈
    【个人项目总结】C#四则运算表达式生成程序
    软件工程驻足篇章:第十七周和BugPhobia团队漫长的道别
    软件工程反思篇章:第七周和进阶团队项目感想反思
  • 原文地址:https://www.cnblogs.com/yaohan/p/5489707.html
Copyright © 2011-2022 走看看