zoukankan      html  css  js  c++  java
  • pythoning——7:Python的内置函数

    abs(number)

    返回一个数的绝对值

    all(iterable)和any(iterable)

    如果所有iterable都为真,则all返回True,否则返回False

    如果任一iterable为真,则any返回True,否则返回False

    >>> all([1==1,1<2,"asdf",[1],True,''])
    False
    >>> all([1==1,1<2,"asdf",[1],True])
    True
    >>> any(["",None,False,1==1])
    True
    >>> any(["",None,False])
    False

    ascii(object)

    将基本的数据类型转换为ascii码

    bin(number),oct(number),hex(number)

    bin将10进制数转换为2进制

    oct将10进制数转换为8进制

    hex将10进制数转换为16进制

    >>> a = 50
    >>> bin(a)
    '0b110010'
    >>> oct(a)
    '0o62'
    >>> hex(a)
    '0x32'

    bool(object)

    将对象转换为bool类型的数据

    >>> bool('')
    False
    >>> bool(1)
    True
    >>> bool([1])
    True

    bytearray(str,encoding)

    将字符串转换为字节码序列,需指明编码方式

    >>> bytearray('安全生产',encoding='utf-8')
    bytearray(b'xe5xaex89xe5x85xa8xe7x94x9fxe4xbaxa7')

    bytes(str,encoding)

    将字符串转换为字节码,需指明编码方式

    >>> bytes("安全生产",encoding='utf-8')
    b'xe5xaex89xe5x85xa8xe7x94x9fxe4xbaxa7'

    callable(object)

    检查对象是否可被调用

    >>> name = "fukuda"
    >>> def fun():
    ...     pass
    ...
    >>> callable(name)
    False
    >>> callable(fun)
    True

    chr(number)和ord(char)

    chr返回ASCII码为给定数字的字符

    ord返回给定的字符的ASCII码

    >>> chr(65)
    'A'
    >>> ord('A')
    65

    classmethod(func)和staticmethond(func)

    classmethod通过一个实例方法创建类的方法(help里面如斯翻译,太绕了现在不太理解,以后会懂吧。呵呵呵呵呵O(∩_∩)O哈哈~)简言之,应该就是可以被子类重写的吧,这样那样的。

    staticmethond通过一个实例方法创建一个静态(类)的方法,恩,同上,不可被子类重写这样那样的。

    待完善

    compile、exec、eval

    complie 将字符串编译为python可执行代码

    exec执行,可执行任何,但无返回值

    eval执行,只能执行表达式

    a = "print ('123')"
    r = compile( a, "<string>" , 'exec')
    exec(r)
    a = ""
    a = "print ('123')"
    r = compile(a, "<string>", 'eval')
    eval(r)

    complex

    通过实数和可选的虚数创建一个复数

    delattr(object,name),getattr(object,name),setattr(obj,name),hasattr(obj,name)

    delattr删除实例中的某个属性

    getattr获取实例中的某个属性

    setattr重新赋值实例中的某个属性

    hasattr查看是否实例中有某个属性

    这里用到了类映射,所以

    代码待补全

    dict(iteralbe)

    构造一个字典,可选择从映射或键值对组成的列表构造。

    dir(object)

    查看实例、方法、类可调用的功能,返回值为列表

    >>> dir(str)
    ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__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']

    divmod(num1,num2)

    返回一个元组,为num1除以num2得到的(商,余)

    >>> divmod(10,3)
    (3, 1)

    enumberate(iterable)

    遍历iterable中所有迭代项

    >>> a=[1,2,3,4]
    >>> for i ,j in enumerate(a):
    ...     print(i,j)
    ...
    0 1
    1 2
    2 3
    3 4

    filter(fun,sequence),map(fun,sequence,...)

    filter返回从给定序列中函数返回真的元素列表

    map创建有给定函数function应用到所给提供的sequence每个项目是返回的值组成的列表

    总之,filter只可做真假过滤,而map可以做逻辑运算,这样那样的。

    def fun(arg):
        if arg != 2:
            return True
        else:
            return False
    li = [1, 2, 3, 4]
    re = filter(fun, li)
    print(type(re))
    print(list(re))
    li = [1, 2, 3, 4, 5]
    re = filter(lambda a: a > 2, li)
    re = list(re)
    print(re)
    li = [1, 2, 3, 4, 5]
    re = map(lambda a: a+10, li)
    re2 = map(lambda a: a>2, li)
    print(list(re))
    print(list(re2))
    li = [1, 2, 3, 4, 5]
    re = map(lambda a:a+10,list(filter(lambda a:a>2,li)))
    print (list(re))

    float(obj)

    将其他基本数据类型转换为浮点型数据

    format(str)

    应用于字符串的格式化

    frozenset([iterable])

    创建一个不可变的set

    >>> a = frozenset([1,2,3,4,5])
    >>> a.add(7)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'frozenset' object has no attribute 'add'

    globals(),locals()

    globals查看所有全局变量

    locals查看所有局部变量

    hash(obj)

    为给定的实例创建一个hash值

    >>> def fun():
    ...     pass
    ...
    >>> hash(fun)
    -2146274858
    >>> hash("a")
    -462022166

    help()

    python神器。可以查看方法,对象,类提供的功能,具体的哦。所以写代码时,备注也是很关键的。

    >>> def fun():
    ...     '''this is help'''
    ...     pass
    ...
    >>> help(fun)
    Help on function fun in module __main__:
    
    fun()
        this is help

    id(obj)

    返回obj的内存地址

    input(str)

    键盘输入

    int()str()list()set()

    isinstance(obj,class)

    查看obj是否为class的实例对象

    >>> isinstance('a',str)
    True

    issubclass(class1,class2)

    查看class1是否为class2的子类(每个类都是自己的子类)

    >>> class obj1:
    ...     pass
    ...
    >>> issubclass(obj1,obj1)
    True
    >>> issubclass(obj1,str)
    False

    max(num1,num2),min(...),sum(...)

    max返回最大值

    min返回最小值

    sum返回和

    range(num1,num2)

    返回一个从num1到num2-1的序列,前包后不包。

    sorted(iterable)

    序列的排序

  • 相关阅读:
    PAT 1088. Rational Arithmetic
    PAT 1087. All Roads Lead to Rome
    PAT 1086. Tree Traversals Again
    PAT 1085. Perfect Sequence
    PAT 1084. Broken Keyboard
    PAT 1083. List Grades
    PAT 1082. Read Number in Chinese
    求最大公因数
    [转载]Latex文件转成pdf后的字体嵌入问题的解决
    [转载]Matlab有用的小工具小技巧
  • 原文地址:https://www.cnblogs.com/fukuda/p/5544370.html
Copyright © 2011-2022 走看看