美文网首页
python基础

python基础

作者: 逃淘桃 | 来源:发表于2018-06-12 15:26 被阅读0次

    python


    2018-5-21

    1. python中的*args**kwargs
      首先我们应该知道,并不是必须写成*args**kwargs,变量前的*是必须的,可以写成*var**vars,而写成*args**kwargs只是一个通俗的命名约定。
      *args**kwargs主要用于函数定义,可以将不定量的参数传递给一个函数。
      *args用来发送一个非键值对的可变数量的参数列表给一个函数。
      **kwargs允许将不定长度的键值对作为参数传递给一个函数,如果想在一个函数里处理带有名字的参数,应该使用**kwargs

    2.python中内建函数isinstance的用法以及与type的区别
    语法:isinstance(object, classinfo);用来判断对象类型。其中,object是变量,classinfo是类型即(tuple,dict,int,float,list,bool等)和class类,如参数object是classinfo类的实例,或者object是classinfo类的子类的一个实例,返回True,若object不是给定类型的实例,则返回结果总是False。若classinfo不是一种数据类型或者由数据类型构成的元组,将引发一个TypeError异常。
    isinstance和type都可用来判断对象类型,但是对于一个class类的子类对象类型判断,type就不行,而isinstance可以。

    3.python中子类调用父类的方法,super().__init__():

      形式:
    class A(object):
      def __init__(self, xing, gender):
        self.namea = 'aaa'
        self.xing = xing
        self.gender = gender
      def funca(self):
        print("function a :%s" %self.namea)
    class B(A):
      def __init__(self, xing, age):
        super(B,self).__init__(xing, age)
          self.nameb = 'bbb'
          self.xing = xing.upper()
          self.age = age + 1
      def funcb(self):
        print("function b: %s"%self.nameb)
    
    b = B("lin", "man", 22)
    
    print(b.nameb)
    --->>bbb
    
    print(b.namea)
    ---->>aaa
    
    print(b.xing)
    --->>LIN
    
    print(b.age)
    --->>23
    
    b.funcb()
    --->>function b: bbb
    b.funca()
    --->>function a: aaa
    
    print(b.gender)
    --->>22
    

    通过验证,可以得出以下结论:

    • B类可以继承A类,在B类的基础上可以调用A类所有的方法,代码最后的b.funcb()b.funca()可以实现。
    • A,B同时拥有__init__,B会改写A中的__init__方法,A类的方法失效。
    • super函数可以调用A父类中的属性,如namea,xing,当B中有同名属性时覆盖A中的同名属性,但调用函数时总是先查找它自身的定义,如果没有定义,则顺着继承链向上查找,直到在某个父类中找到为止。
    • B类__init__参数需大于或者等于A父类的__init__方法,因为super初试化了,参数量为父类参数量。
    • super函数原理:super().__init__(***,***)中的***参数为类B中输入的参数,但与类A中参数名相对应。
      4.python中强大的format函数
      自从python2.6开始,新增了一种格式化字符串的函数str.format(),次函数可以快速的处理各种字符串。
      语法:它用{}来代替%
    >>>"{} {}".format("hello", "world")  #不设置指定位置,按默认顺序
    'hello world'
    
    >>>"{0} {1}".format("hello", "word")  #设置指定位置
    'hello world'
    
    >>>"{1} {0} {1}".format("hello","world")  #设置指定位置
    'world hello world'
    

    也可以设置参数:

    print("这是一个: {test_name},作者是:{author}".format(test_name="test", author="sherry"))
    --->>这是一个:test,作者是:sherry
    

    也可以通过列表索引设置参数

    my_list = ['test', 'sherry']
    print("这是一个:{0[0]},作者是:{0[1]}".format(my_list))  #"0"是必须的
    --->>这是一个:test,作者是:sherry
    

    2018-5-24

    python

    1.python中的OrderedDict()的使用
    很多人认为python中的字典是无序的,因为它是按照hash来存储的,但是python中有一个模块collections,提供了很多有用的集合类。里面自带了一个子类OrderedDict,实现了对字典对象中元素的排序。OrderedDict会根据放入元素的先后顺序进行排序,所以输出的值是排好序的。OrderedDict对象是字典对象,如果顺序不同,那么python也会把他们当成是两个不同的对象。


    2018-5-25

    python

    1.python中数组和矩阵乘法及使用总结

    • 对数组的运算
    import numpy as np
    
    a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    a = np.mat(a)
    a
    
    --->>
    matrix([[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]])
    
    b = np.array([[7, 8, 9],[4, 5, 6],[1, 2, 3]])
    b = np.mat(b)
    b
    
    --->>
    matrix([[7, 8, 9],
            [4, 5, 6],
            [1, 2, 3]])
    
    a + b#矩阵的加减运算和数组运算一致,在对应位置相加减
    
    --->>
    matrix([[ 8, 10, 12],
            [ 8, 10, 12],
            [ 8, 10, 12]])
    
    a * b#矩阵的乘用*即可表示
    
    --->>
    matrix([[ 18,  24,  30],
            [ 54,  69,  84],
            [ 90, 114, 138]])
    
    b * a
    
    --->>
    matrix([[102, 126, 150],
            [ 66,  81,  96],
            [ 30,  36,  42]])
    
    np.dot(b, a)# 使用dot与*的效果一样
    
    --->>
    matrix([[102, 126, 150],
            [ 66,  81,  96],
            [ 30,  36,  42]])
    
    np.dot(a, b)
    
    --->>
    matrix([[ 18,  24,  30],
            [ 54,  69,  84],
            [ 90, 114, 138]])
    
    c = np.array([1, 2, 3])#构建一个一行三列的数组
    c
    
    --->>
    array([1, 2, 3])
    
    a * c# 不符合矩阵运算规则
    
    --->>
    ValueError                                Traceback (most recent call last)
    <ipython-input-19-fc01a05f2628> in <module>()
    ----> 1 a * c
    
    /home/icrclsc/anaconda3/lib/python3.5/site-packages/numpy/matrixlib/defmatrix.py in __mul__(self, other)
        307         if isinstance(other, (N.ndarray, list, tuple)) :
        308             # This promotes 1-D vectors to row vectors
    --> 309             return N.dot(self, asmatrix(other))
        310         if isscalar(other) or not hasattr(other, '__rmul__') :
        311             return N.dot(self, other)
    
    ValueError: shapes (3,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)
    
    c * a
    
    --->>
    matrix([[30, 36, 42]])
    
    np.dot(c, a)# 与矩阵运算一致
    
    --->>
    matrix([[30, 36, 42]])
    
    np.dot(a, c)# 自动将a转换成3行1列参与运算,返回结果格式已经变为1行3列而非3行一列的矩阵
    
    --->>
    matrix([[14, 32, 50]])
    
    c =c.reshape(3, 1)
    c
    
    --->>
    array([[1],
           [2],
           [3]])
    
    a * c
    
    --->>
    matrix([[14],
            [32],
            [50]])
    
    c * a
    
    --->>
    ValueError                                Traceback (most recent call last)
    <ipython-input-25-608e57f1304c> in <module>()
    ----> 1 c * a
    
    /home/icrclsc/anaconda3/lib/python3.5/site-packages/numpy/matrixlib/defmatrix.py in __rmul__(self, other)
        313 
        314     def __rmul__(self, other):
    --> 315         return N.dot(other, self)
        316 
        317     def __imul__(self, other):
    
    ValueError: shapes (3,1) and (3,3) not aligned: 1 (dim 1) != 3 (dim 0)
    
    • 矩阵求逆,转置,求迹
    a.T# a 的转置
    
    --->>
    matrix([[1, 4, 7],
            [2, 5, 8],
            [3, 6, 9]])
    
    a.H# a的共轭转置
    
    --->>
    matrix([[1, 4, 7],
            [2, 5, 8],
            [3, 6, 9]])
    
    b = np.eye(3)
    b
    
    --->>
    array([[1., 0., 0.],
           [0., 1., 0.],
           [0., 0., 1.]])
    
    b = b * 3
    b
    
    --->>
    array([[3., 0., 0.],
           [0., 3., 0.],
           [0., 0., 3.]])
    
    b = np.mat(b)
    b
    
    matrix([[3., 0., 0.],
            [0., 3., 0.],
            [0., 0., 3.]])
    
    b.I
    
    matrix([[0.33333333, 0.        , 0.        ],
            [0.        , 0.33333333, 0.        ],
            [0.        , 0.        , 0.33333333]])
    
    np.trace(b)
    
    9.0
    

    2018-5-29

    1.python在使用变量的时候没有声明变量类型,这一点和C语言不同,但是变量还可以工作,因为在python中类型是在运行过程中自动解决的,而不是通过代码声明,这意味着没有必要事先声明变量。在python中,我们要明确一个概念:变量名和对象是划分开的,变量名永远没有任何关联的类型信息,类型是和对象相关联的,而不存在于变量名中,一个变量名当第一次被赋值的时候被创建,而当显得赋值表达式出现时,他会马上被当前新引用的对象所代替,这就是python所谓的动态类型机制


    2018-06-05

    1.python的hasattr()函数

    • hasattr()函数用于判断对象是否包含对应的属性。语法为hasattr(object, name),其中object表示对象,name表示字符串或者属性名。

    2018-07-16

    1. pythonmap()函数
      map()函数接受两个参数,一个是函数,一个是序列。map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回。
      f(x) = x^2
    2. join()函数
      语法:sep.join(seq)
      参数说明:
      sep:分隔符,可以为空
      seq:要连接的元素序列、字符串、元组、字典
      即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串。
    3. os.path.join()函数
      语法:os.path.join(path1[,path2[,...]])
      返回值:将多个绝对路径组合后返回。

    2018-07-17

    1.python time strftime()方法
    描述:Python time strftime()函数接收以时间元组,并返回可读字符串表示当地时间,格式由参数format决定。
    语法:

    time.strftime(format[,t])
    

    format:格式字符串
    t:可选的参数t是一个struct_time对象
    返回值:返回可读字符串表示的当地时间。


    2018-07-24

    1.python函数的rstriplstrip

    • lstrip = left strip = 去除(字符串)左边的 = strip leading = 去除(字符串)开始的
    • rstrip = right strip = 去除(字符串)右边的 = strip ending = 去除(字符串)末尾的
    • strip = strip left and right = 去除(字符串)左边和右边的
      默认的空白格Whitespace,所谓的空白格一般是指:空格本身,回车\r,换行\n,制表符\t,换页符\f
      对应于正则表达式中的:\s == [\r\n\t\f]
      2.lambda是什么?
    func = lambda x:x+1
    print(func(1))
    # 2
    

    可以这样认为,lambda作为一个表达式,定义了一个匿名函数,上例的代码x为入口参数,x+1为函数体,在这里lambda简化了函数定义的书写形式,使得代码更加简洁,但是使用函数的定义方式更为直观。


    2018-07-25

    1.python中re模块的compile函数如何用?

    • python中的re.compile(pattern, flag=0)compile a regular expression pattern, returning a pattern object即编一个亿正则表达式模式,返回一个模式对象。然后可以使用pattern实例处理文本并返回匹配结果。

    2.os.path.basename()的作用:

    • 如下
    path =  'D:\TEST'
    os.path.basename(path) = TEST
    

    返回path最后的文件名。

    3.python字符串格式化(%占位符操作)
    格式化字符串时,python使用一个字符串作为模板,模板中有格式符,这些格式符为真实值预留位置,并说明真实数字应该呈现的格式,python用一个tuple将多个值对应一个格式符。

    print("I'm %s. I'm %d year old" % ('Vamei', 99))
    # I'm Vamei. I'm 99 year old
    

    4.python中计算时间差的secondstotale_seconds
    其中seconds获取的仅仅是时间差的秒数,忽略微秒数和天数。
    total_seconds计算是两个时间之间的总差。
    total_seconds() = (td.microseconds+ (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 # td是timedelta对象

    import datetime
    
    t1 = datetime.datetime.strptime("2018-7-25 16:10:00", "%Y-%m-%d %H:%M:%S")
    t2 = datetime.datetime.strptime("2018-7-25 18:10:00", "%Y-%m-%d %H:%M:%S")
    interval_time = (t2 - t1).seconds
    total_interval_time = (t2 - t1).total_seconds()
    print(interval_time) # 7200
    print(total_interval_time) # 7200.0
    
    import datetime
    
    t1 = datetime.datetime.strptime("2018-7-23 16:10:00", "%Y-%m-%d %H:%M:%S")
    t2 = datetime.datetime.strptime("2018-7-25 18:10:00", "%Y-%m-%d %H:%M:%S")
    interval_time = (t2 - t1).seconds
    total_interval_time = (t2 - t1).total_seconds()
    print(interval_time) # 7200
    print(total_interval_time) # 180000.0
    

    2018-07-27

    1.python中的print打印

    • 打印字符串
    string = "hello"
    #%s打印的结果是hello
    print("string = %s" % string)  # output:string = hello
    #%2s意为字符串的长度为2,当原字符串的长度超过2的时候,按原长度打印
    print("string = %2s" % string)  # output:string = hello
    # %7s意为字符串的长度为7,当原字符长度小于7时,在原字符的左侧补空格
    print("string = %7s" % string)  #output:string =   hello
    # %-7s意为字符串的长度为7,当原字符长度小于7时,在原字符的右侧补空格
    print("string = %-7s?" % string)  #output:string = hello  ?
    #%.2s意思是截取字符串的前2个字符,所以%.2s的打印结果是he 
    print "string=%.2s" % string    # output: string=he 
    #%.7s意思是截取字符串的前7个字符,当原字符串长度小于7时,即是字符串本身,    
    #所以%.7s的打印结果是hello
    print "string=%.7s" % string    # output: string=hello 
    #%a.bs这种格式是上面两种格式的综合,首先根据小数点后面的数b截取字符串,    
    #当截取的字符串长度小于a时,还需要在其左侧补空格
    print "string=%7.2s" % string   # output: string=     he    
    print "string=%2.7s" % string   # output: string=hello    
    print "string=%10.7s" % string  # output: string=     hello 
    #还可以用%*.*s来表示精度,两个*的值分别在后面小括号的前两位数值指定    
    print "string=%*.*s" % (7,2,string)      # output: string=     he
    
    • 打印整型
    num=14    
        
    #%d打印时结果是14    
    print "num=%d" % num            # output: num=14    
        
    #%1d意思是打印结果为1位整数,当整数的位数超过1位时,按整数原值打印,所以%1d的打印结果还是14    
    print "num=%1d" % num           # output: num=14    
        
    #%3d意思是打印结果为3位整数,当整数的位数不够3位时,在整数左侧补空格,所以%3d的打印结果是 14    
    print "num=%3d" % num           # output: num= 14    
        
    #%-3d意思是打印结果为3位整数,当整数的位数不够3位时,在整数右侧补空格,所以%3d的打印结果是14_    
    print "num=%-3d" % num          # output: num=14_    
        
    #%05d意思是打印结果为5位整数,当整数的位数不够5位时,在整数左侧补0,所以%05d的打印结果是00014    
    print "num=%05d" % num          # output: num=00014    
        
    #%.3d小数点后面的3意思是打印结果为3位整数,    
    #当整数的位数不够3位时,在整数左侧补0,所以%.3d的打印结果是014    
    print "num=%.3d" % num          # output: num=014    
        
    #%.0003d小数点后面的0003和3一样,都表示3,意思是打印结果为3位整数,    
    #当整数的位数不够3位时,在整数左侧补0,所以%.3d的打印结果还是014    
    print "num=%.0003d" % num       # output: num=014    
        
    #%5.3d是两种补齐方式的综合,当整数的位数不够3时,先在左侧补0,还是不够5位时,再在左侧补空格,    
    #规则就是补0优先,最终的长度选数值较大的那个,所以%5.3d的打印结果还是  014    
    print "num=%5.3d" % num         # output: num=  014    
        
    #%05.3d是两种补齐方式的综合,当整数的位数不够3时,先在左侧补0,还是不够5位时,    
    #由于是05,再在左侧补0,最终的长度选数值较大的那个,所以%05.3d的打印结果还是00014    
    print "num=%05.3d" % num        # output: num=00014    
        
    #还可以用%*.*d来表示精度,两个*的值分别在后面小括号的前两位数值指定    
    #如下,不过这种方式04就失去补0的功能,只能补空格,只有小数点后面的3才能补0    
    print "num=%*.*d" % (04,3,num)  # output: num= 014
    
    • 打印浮点型
    import math    
        
    #%a.bf,a表示浮点数的打印长度,b表示浮点数小数点后面的精度    
        
    #只是%f时表示原值,默认是小数点后5位数    
    print "PI=%f" % math.pi             # output: PI=3.141593    
        
    #只是%9f时,表示打印长度9位数,小数点也占一位,不够左侧补空格    
    print "PI=%9f" % math.pi            # output: PI=_3.141593    
        
    #只有.没有后面的数字时,表示去掉小数输出整数,03表示不够3位数左侧补0    
    print "PI=%03.f" % math.pi          # output: PI=003    
        
    #%6.3f表示小数点后面精确到3位,总长度6位数,包括小数点,不够左侧补空格    
    print "PI=%6.3f" % math.pi          # output: PI=_3.142    
        
    #%-6.3f表示小数点后面精确到3位,总长度6位数,包括小数点,不够右侧补空格    
    print "PI=%-6.3f" % math.pi         # output: PI=3.142_    
        
    #还可以用%*.*f来表示精度,两个*的值分别在后面小括号的前两位数值指定    
    #如下,不过这种方式06就失去补0的功能,只能补空格    
    print "PI=%*.*f" % (06,3,math.pi)   # output: PI=_3.142 
    

    2018-08-02

    1.python内置函数sorted()函数的用法

    • 对于python的内置函数sorted(),先拿来和list中的成员函数list.sort()进行下对比,在本质上,list的排序和内置函数sorted的排序是差不多的,连参数都基本上是一样的。主要的区别在于list.sort()是对已经存在的列表进行操作,进而可以改变进行操作的列表,而内置函数sorted()返回的是一个新的list,而不是在原来的基础上进行操作。
    • 使用python中自带的help()看看对sorted()是如何定义的:
    >>> help(sorted)
    Help on built-in function sorted in module builtins:
    
    sorted(iterable, key=None, reverse=False)
        Return a new list containing all items from the iterable in ascending order.
    
        A custom key function can be supplied to customise the sort order, and the 
        reverse flag can be set to request the result in descending order.
    

    help()可以看到,闯进去的是一个可迭代的数据,返回一个新的列表,注意是新的列表!例子如下:

    >>> g=[1, 4, 2, 6, 7, 3, 8]
    >>> sorted(g)
    [1, 2, 3, 4, 6, 7, 8]
    >>> sorted((1, 4, 8, 9, 3, 6))
    [1, 3, 4, 6, 8, 9]
    >>> sorted('gadtser')
    ['a', 'd', 'e', 'g', 'r', 's', 't']
    

    由上可以看到,只要是可迭代的对象数据,都能够进行排序,生成一个排序后的列表。

    • 如果想要逆排序呢?很简单,只要将可选函数reverse设置为True即可。
    >>> sorted((1, 4, 2, 8, 9, 3, 5), reverse=True)
    [9, 8, 5, 4, 3, 2, 1]
    

    高级用法

    • 有时候我们要处理的数据内的元素不是一维的,而是二维的甚至是多维的,那要怎么进行排序呢?这个时候sorted()函数内的key参数就派上用场了。从帮助上可以看到,key参数可以传入一个自定义函数,那么,该如何使用呢?下面是几个例子:
    >>>l=[('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]
    >>>sorted(l, key=lambda x:x[0])
    Out[39]: [('a', 1), ('b', 2), ('c', 6), ('d', 4), ('e', 3)]
    >>>sorted(l, key=lambda x:x[0], reverse=True)
    Out[40]: [('e', 3), ('d', 4), ('c', 6), ('b', 2), ('a', 1)]
    >>>sorted(l, key=lambda x:x[1])
    Out[41]: [('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)]
    >>>sorted(l, key=lambda x:x[1], reverse=True)
    Out[42]: [('c', 6), ('d', 4), ('e', 3), ('b', 2), ('a', 1)]
    

    这样,列表里面的每一个元素都为二维元组,key参数传入了一个lambda函数表达式,其x就代表列表里的每一个元素,然后分别利用索引返回元素内的第一个和第二个元素,这就代表了sorted()函数利用了哪一个元素进行排列,而reverse参数就如同上面所讲的一样,起到逆排的作用。
    当然,正如一开始讲到的那样,如果想要对列表直接进行排序操作,可以用sort()来做:

    >>>l.sort(key=lambda x : x[1])
    >>>l
    Out[45]: [('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)]
    >>>l.sort(key=lambda x : x[1], reverse=True)
    >>>l
    Out[47]: [('c', 6), ('d', 4), ('e', 3), ('b', 2), ('a', 1)]
    

    对于三维及以上的数据排排序,上述方法同样适用。


    2018-08-02

    1.python的itertools模块
    python itertools模块详解

    • itertools用于高效循环的迭代函数集合

    2018-08-07

    1.pythonassert断言的作用:

    • 根据python官方文档解释:Assert statements are a convenient way to insert debugging assertions into a program.
    • 一般用法: assert condition 用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError来。逻辑上等同于:
      if not condition:
              raise AssertionError()
    • 如何为assert断言语句添加异常参数:
      assert的异常函数,其实就是在断言表达式后添加字符串信息,用来解释断言并更好的知道哪里出了问题。格式如下:
      assert expression [, arguments]
      assert 表达式 [,参数]

    2018-08-08

    1. python中获取路径os.getcwd()os.path.dirname(os.path.realpath(__file__))的区别与对比:
    • 如果在同一个脚本中使用这两个函数都能获得当前脚本所在的目录
    • 如果是存在调用,os.path.dirname(os.path.realpath(__file__))获取的是__file__所在的脚本路径,而os.getcwd()获取的是当前最外层调用的脚本路径,即如果A调用B,那么os.getcwd()获取的就是A所在的路径。

    2018-08-10

    1.python中的内嵌函数enumerate()函数
    enumerate()函数用于将一个可遍历的数据对象(如列表、元组或者字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中,python2.3以上版本可用,2.6添加start参数。

    • 语法:`enumerate(sequence,[start=0])
    • 参数:
      sequence:一个序列、迭代器或者其他支持迭代对象。
      start:下标起始位置。
    • 例子:
    >>>i = 0
    >>> seq = ['one', 'two', 'three']
    >>> for element in seq:
    ...     print i, seq[i]
    ...     i +=1
    ... 
    0 one
    1 two
    2 three
    

    2018-08-14

    1. python字典中.get()方法:
      语法:
      dict.get(key, default=None),参数key为字典中要查找的键,default为如果指定键的值不存在时,返回该默认值。

    2018-08-15

    1.python zip()函数:

    • 描述:zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表,如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用*号操作符,可以将元组解压为列表。(zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。)
    • 语法:`zip([iterable,...]),其中iterable为一个或者多个迭代器。
    >>>a = [1,2,3]
    >>> b = [4,5,6]
    >>> c = [4,5,6,7,8]
    >>> zipped = zip(a,b)     # 打包为元组的列表
    [(1, 4), (2, 5), (3, 6)]
    >>> zip(a,c)              # 元素个数与最短的列表一致
    [(1, 4), (2, 5), (3, 6)]
    >>> zip(*zipped)          # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
    [(1, 2, 3), (4, 5, 6)]
    

    相关文章

      网友评论

          本文标题:python基础

          本文链接:https://www.haomeiwen.com/subject/uytreftx.html