zoukankan      html  css  js  c++  java
  • python学习笔记14:常用内置函数

    chr()和ord()

    ord():将char转为Unicode(0~65535)值(在python2中是ASCII(0~255)值)
    chr(): 将Unicode(0~65535)值转为char(在python2中是ASCII(0~255)值)
    注意:unichr() 在python3中去掉,由chr代替。

    >>> ord(‘a’)
    97
    >>> ord(‘
    ’)
    10
    
    >>> chr(97)
    ‘a’
    >>> chr(10)
    ‘
    ’
    

    exec和eval

    exec执行字符串形式的代码(python语句,做某事),返回None

    >>> exec('a = 6') # 相当于把a=6这条语句放在此处执行
    >>> a
    6
    

    exec也可以执行多行代码:

    >>> a = [0,1,2,3]
    >>>
    
    >>> # exec多行代码,代码放到长字符串中,
    >>> # 注意字符串中代码的缩进,要顶格写,不要管exec语句外的缩进
    >>> s_code='''
    ... print(a)      # exec语句可以访问正常代码中的变量
    ... a.append('s') # exec语句可以访问修改代码中的变量
    ... print(a)
    ... '''
    >>>
    >>> exec(s_code)
    [0, 1, 2, 3]
    [0, 1, 2, 3, 's']
    >>>
    >>> a             # exec语句对变量的修改,会影响到exec语句外
    [0, 1, 2, 3, 's']
    >>>
    
    >>> # exec多行代码,代码放到list中
    >>> list_code = list()
    >>> list_code.append('print(a)')
    >>> list_code.append('a.append("L")')
    >>> list_code.append('print(a)')
    >>>
    >>> exec('
    '.join(list_code)) # 通过换行符连接各语句
    [0, 1, 2, 3, 's']
    [0, 1, 2, 3, 's', 'L']
    >>>
    >>> exec(';'.join(list_code)) # 通过分号连接各语句
    [0, 1, 2, 3, 's', 'L']
    [0, 1, 2, 3, 's', 'L', 'L']
    >>>
    >>> a
    [0, 1, 2, 3, 's', 'L', 'L']
    >>>
    

    eval执行字符串形式的表达式,返回表达式的值

    >>> a = eval('2*3')
    >>> a
    6
    >>> b = eval('a==6')
    >>> b
    True
    

    id()

    返回一个对象的序号,转成16进制后即内存地址。

    >>> class Test():
    ...pass
    ...
    >>> t0 = CTest()
    >>> t0
    <__main__.CTest object at 0x00328D710>
    >>> id(t0)
    53008144
    >>> '{:x}'.format(id(t0)) # id()返回的为10进制数,转为16进制后为内存地址;
    328d710
    

    map(func, *iterables)

    参数:map()函数接收两个参数:一个函数、一个Iterable序列。
    功能:将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回, map()主要是把运算规则抽象化;
    返回值:map object,可以通过list(map object)将之转为list
    例1:

    >>> def f(x):
    ...     return x*x
    ...
    >>> r = map(f, [1,2,3])
    >>> r
    <map object at 0x2b*******>
    >>> list(r) # r是一个Iterator,使用list()函数把整个序列计算出来
    [1, 4, 9]
    

    例2:

    >>> list(map(str, range(3))) # 把列表的int转为str;
    ['0', '1', '2']
    

    reduce(function, sequence[, initial])

    参数:reduce()函数接收三个参数:一个函数、一个Iterable序列,还有一个初始值。
    功能:将传入的函数作用在序列上,把函数计算结果一直和序列的下一个元素做累积计算;
    reduce(f, [x0, x1, x2, x3]) 等价于 f(f(f(x0, x1), x2), x3)

    >>> import functools
    >>> def add(x,y):
    ...     return x+y
    ...
    >>> functools.reduce(add, [1,3,5,7,9]) # 将list元素累加
    25
    >>> functools.reduce(add, [1,3,5,7,9], 100) #将list累加,初始值为100
    125
    

    filter(function or None, iterable)

    参数:filter()函数接收两个参数:一个函数,一个序列;与map类似。
    功能:把传入的函数依次作用于每个元素,根据函数返回值是True或False决定元素是否保留;
    返回值:filter object

    >>> def is_odd(n):
    ...     return n%2==1
    ...
    >>> r = filter(is_odd, range(9))
    >>> r
    <filter object at 0x2b******>
    >>> list(r)
    [1,3,5,7]
    

    zip(iterable[, iterable, ...])

    语法:zip(iterable[, iterable, ...])
    作用:将参数中对应的元素打包成一个个元组;
    返回值:返回元组组成的对象(可以节约内存),可以使用list()将之转为列表;
    参数:iterable,一个或多个迭代器
    例1

    >>> lst0 = [1, 2, 3]
    >>> lst1 = [4, 5, 6]
    >>> lst2 = [7, 8, 9, 10, 11]
    

    zip返回的是zip对象,可以用list(),将之转为列表

    >>> zip_0 = zip(lst0, lst1)
    >>> zip_0 # 是一个对象
    <zip object at 0x2ad*******>
    >>> list(zip_0) #通过list()把它转为列表
    [(1, 4), (2, 5), (3, 6)]
    

    如果两个iterable不等长,取最短的

    >>> list(zip(lst0, lst2)) # 如果两个iterable不等长,取最短的
    [(1, 7), (2, 8), (3, 9)]
    

    如果iterable只有一个,则元组元素就只有一个

    >>> list(zip(lst0)) # 如果iterable只有一个,则元组元素就只有一个
    [(1,), (2,), (3,)]
    

    如果iterable有3个,则元组元素就有3个

    >>> list(zip(lst0, lst1, lst2)) #如果iterable有3个,则元组元素就有3个
    >>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    

    zip(*XX),将zip对象XX做解压,返回list

    >>> a0, a1 = zip(*[(1, 4), (2, 5), (3, 6)])
    >>> a0
    (1, 2, 3)
    >>> a1
    (4, 5, 6)
    

    range()

    语法:
    ?range(stop)
    ?range(start, stop[, step])
    参数:
    ?start:起始值,可选,默认为0;
    ?stop:结束值,必选;注意:结束值不包含在返回的object中;
    ?step:步长,可选,默认为1;
    返回值:class 'range'

    range(i, j) 包含:i, i+1, i+2, ..., j-1;

    >>> range(3)
    range(0, 3)
    >>> type(range(3))
    <class 'range'>
    >>> list(range(3)) # 不包含3
    [0, 1, 2]
    

    type(), isinstance(), dir()

    type()

    type()函数用来获取对象类型

    type(123) # <class 'int'>  
    type(d)   # <class '__main__.Dog'>  
    type(abs) # <class 'builtin_function_or_method'> 内置函数  
    

    type()返回的是class类型,所以相同类型的比较会返回True, 直接与类型比较也返回True:

    type(123) == type(456) # True  
    type(123) == int       # True  
    

    使用types包
    常用的类型有:
    types.FunctionType,
    types.BuiltinFunctionType,
    types.LambdaType,
    types.GeneratorType

    >>> import types    
      
    >>> def fn()    
    ...     pass    
    ...    
    >>> type(fn) == types.FunctionType          # True  
    >>> type(abs) == types.BuiltinFunctionType  # True  
    >>> type(lambda x:x) == types.LambdaType    # True  
    >>> type((x for x in range(10))) == types.GeneratorType  # True  
    

    isinstance()

    语法:isinstance(obj, class_or_tuple, /)
    参数:参数2可以是一个class,也可以是class组成的元组,元组中的class是“或”的关系;

    对于有继承关系的class,可以使用isinstance()判断class类型;

    >>> class A(object):  
    ...     pass  
    ...  
    >>> class B(A):  
    ...     pass  
    ...  
    >>> b0 = B()  
    >>> isinstance(b0, B) # True, b0是B的实例  
    >>> isinstance(b0, A) # True, b0也是A的实例  
    

    参数2可以是一个元组

    >>> isinstance((1, 2, 3), list          ) # False, 不是list  
    >>> isinstance((1, 2, 3), tuple         ) # True , 是tuple  
    >>> isinstance((1, 2, 3), (list, tuple)) # True , 是list或tuple  
    

    还可以判断对象是不是可迭代的:

    >>> import collections  
    >>> isinstance('abc'     , collections.Iterable) # True, str可迭代  
    >>> isinstance([1,2,3]   , collections.Iterable) # True, list可迭代  
    >>> isinstance({1:2, 3:4}, collections.Iterable) # True, dict可迭代  
    >>> isinstance(123       , collections.Iterable) # False,int不可迭代  
    

    dir()

    dir()函数用于获取一个对象的所有属性和方法;比如dir('ABC')返回字符串的属性和方法;
    例:先定义一个class

    >>> class Dog():    
    ...     def __init__(self, name):    
    ...         self.name = name    
    ...     def getName(self):    
    ...         return self.name    
    

    使用dir获取属性和方法(这种方式不能区分哪个是属性哪个是方法):

    >>> d0 = Dog('XiaoBai')    
    >>> attrs = [ele for ele in dir(d0) if not ele.startswith('__')]    
    >>> attrs    
    ['getName', 'name']    
    

    hasattr()

    使用hasattr判断某对象是否包含某属性/方法, 然后使用callable判断它是属性还是方法
    例:

    >>> hasattr(d0, 'name') # d0有'name'属性  
    True  
    >>> hasattr(d0, 'getName') # d0有'getName'方法  
    True  
    >>> hasattr(d0, 'age')  
    False  
    >>>   
    >>> callable(d0.name)  
    False  
    >>> callable(d0.getName)  # getName可调用, 它是个方法
    True  
    

    getattr()

    使用getattr和callable联合判断:

    >>> name = getattr(d0, 'name', None)  
    >>> if callable(name):  
    ...     print('name is callable')  
    ... else:  
    ...     print('name is not callable')  
    ...   
    name is not callable  
    >>>   
    >>> getName = getattr(d0, 'getName', None)  
    >>> if callable(getName):  
    ...     print('getName is callable')  
    ...     print(getName()) # 调用方法  
    ... else:  
    ...     print('getName is not callable')  
    ...   
    getName is callable  
    Xiaobai  
    >>>   
    >>> getName  
    <bound method Dog.getName of <__main__.Dog object at 0x2b***>>  
    >>> getName()  
    'Xiaobai'  
    

    setattr()

    使用setattr(), 如果属性存在, 则修改该属性的值, 如果属性不存在, 则添加该属性

    >>> setattr(d0, 'name', 'Dabai') # 设置'name'属性  
    >>> d0.name  
    'Dabai'  
    >>> setattr(d0, 'color', 'White') # 设置不存在的属性,则添加该属性;  
    >>> d0.color  
    'white'  
    
  • 相关阅读:
    9.5---所有字符串的排列组合(CC150)
    9.4---集合子集(CC150)
    9.3---魔术索引(CC150)
    5.3(2)----机器人走方格2(CC150)
    9.2---机器人走方格(CC150)
    9.1---上楼梯(CC150)
    5.3---找最近的两个数(CC150)
    5.8---像素设定(CC150)
    7.4---加法替代运算(CC150)
    4.9---二叉树路径和(CC150)
  • 原文地址:https://www.cnblogs.com/gaiqingfeng/p/13229414.html
Copyright © 2011-2022 走看看