• Python之路第一课Day3--随堂笔记(文件操作)


    一、集合的介绍

    1.集合操作

    集合是一个无序的,不重复的数据组合,它的主要作用如下:

    • 去重,把一个列表变成集合,就自动去重了
    • 关系测试,测试两组数据之前的交集、差集、并集等关系

    常用操作

    s = set([3,5,9,10])      #创建一个数值集合  
      
    t = set("Hello")         #创建一个唯一字符的集合  
    
    
    a = t | s          # t 和 s的并集  
      
    b = t & s          # t 和 s的交集  
      
    c = t – s          # 求差集(项在t中,但不在s中)  
      
    d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中)  
      
       
      
    基本操作:  
      
    t.add('x')            # 添加一项  
      
    s.update([10,37,42])  # 在s中添加多项  
      
       
      
    使用remove()可以删除一项:  
      
    t.remove('H')  
      
      
    len(s)  
    set 的长度  
      
    x in s  
    测试 x 是否是 s 的成员  
      
    x not in s  
    测试 x 是否不是 s 的成员  
      
    s.issubset(t)  
    s <= t  
    测试是否 s 中的每一个元素都在 t 中  
      
    s.issuperset(t)  
    s >= t  
    测试是否 t 中的每一个元素都在 s 中  
      
    s.union(t)  
    s | t  
    返回一个新的 set 包含 s 和 t 中的每一个元素  
      
    s.intersection(t)  
    s & t  
    返回一个新的 set 包含 s 和 t 中的公共元素  
      
    s.difference(t)  
    s - t  
    返回一个新的 set 包含 s 中有但是 t 中没有的元素  
      
    s.symmetric_difference(t)  
    s ^ t  
    返回一个新的 set 包含 s 和 t 中不重复的元素  
      
    s.copy()  
    返回 set “s”的一个浅复制
    
    常用操作
    常用操作之方法1
    list_1 = [1,4,5,7,3,6,7,9]
    list_1 = set(list_1)  #集合
    print(list_1,type(list_1))
    
    list_2 = set([2,6,0,66,22,8,4])
    print(list_1,list_2)
    #交集
    print(list_1.intersection(list_2))
    #并集
    print(list_1.union(list_2))
    #差集
    print(list_1.difference(list_2))
    print(list_2.difference(list_1))
    #子集
    print(list_1.issubset(list_2))  #判断是否是子集
    #父集
    print(list_1.issuperset(list_2))
    #对称差集
    print(list_1.symmetric_difference(list_2))
    
    list_3 = set([1,3,7])
    print(list_3.issubset(list_1))
    #判断有无交集
    print("================================")
    list_3 = set([1,3,7])
    list_4=set([5,6,7,8])
    print(list_3.isdisjoint(list_4))
    #交集
    print(list_1 & list_2)
    #并集
    print(list_1 | list_2)
    #差集
    print(list_1 - list_2)  #in list_1 but not list_2
    #对称差集
    print(list_1^ list_2)
    #子集 subset and upperset
    print(list_1 -  list_2)
    常用操作之方法2

    2. 文件操作

    对文件操作流程

    1. 打开文件,得到文件句柄并赋值给一个变量
    2. 通过句柄对文件进行操作
    3. 关闭文件 

    现有文件如下 

    Somehow, it seems the love I knew was always the most destructive kind
    不知为何,我经历的爱情总是最具毁灭性的的那种
    Yesterday when I was young
    昨日当我年少轻狂
    The taste of life was sweet
    生命的滋味是甜的
    As rain upon my tongue
    就如舌尖上的雨露
    I teased at life as if it were a foolish game
    我戏弄生命 视其为愚蠢的游戏
    The way the evening breeze
    就如夜晚的微风
    May tease the candle flame
    逗弄蜡烛的火苗
    The thousand dreams I dreamed
    我曾千万次梦见
    The splendid things I planned
    那些我计划的绚丽蓝图
    I always built to last on weak and shifting sand
    但我总是将之建筑在易逝的流沙上
    I lived by night and shunned the naked light of day
    我夜夜笙歌 逃避白昼赤裸的阳光
    And only now I see how the time ran away
    事到如今我才看清岁月是如何匆匆流逝
    Yesterday when I was young
    昨日当我年少轻狂
    So many lovely songs were waiting to be sung
    有那么多甜美的曲儿等我歌唱
    So many wild pleasures lay in store for me
    有那么多肆意的快乐等我享受
    And so much pain my eyes refused to see
    还有那么多痛苦 我的双眼却视而不见
    I ran so fast that time and youth at last ran out
    我飞快地奔走 最终时光与青春消逝殆尽
    I never stopped to think what life was all about
    我从未停下脚步去思考生命的意义
    And every conversation that I can now recall
    如今回想起的所有对话
    Concerned itself with me and nothing else at all
    除了和我相关的 什么都记不得了
    The game of love I played with arrogance and pride
    我用自负和傲慢玩着爱情的游戏
    And every flame I lit too quickly, quickly died
    所有我点燃的火焰都熄灭得太快
    The friends I made all somehow seemed to slip away
    所有我交的朋友似乎都不知不觉地离开了
    And only now I'm left alone to end the play, yeah
    只剩我一个人在台上来结束这场闹剧
    Oh, yesterday when I was young
    噢 昨日当我年少轻狂
    So many, many songs were waiting to be sung
    有那么那么多甜美的曲儿等我歌唱
    So many wild pleasures lay in store for me
    有那么多肆意的快乐等我享受
    And so much pain my eyes refused to see
    还有那么多痛苦 我的双眼却视而不见
    There are so many songs in me that won't be sung
    我有太多歌曲永远不会被唱起
    I feel the bitter taste of tears upon my tongue
    我尝到了舌尖泪水的苦涩滋味
    The time has come for me to pay for yesterday
    终于到了付出代价的时间 为了昨日
    When I was young
    当我年少轻狂
    View Code

    基本操作

    f = open('lyrics') #打开文件
    first_line = f.readline()
    print('first line:',first_line) #读一行
    print('我是分隔线'.center(50,'-'))
    data = f.read()# 读取剩下的所有内容,文件大时不要用
    print(data) #打印文件
    f.close() #关闭文件

    打开文件的模式有:

    • r,只读模式(默认)。
    • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
    • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

    "+" 表示可以同时读写某个文件

    • r+,可读写文件。【可读;可写;可追加】
    • w+,写读
    • a+,同a

    "U"表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用)

    • rU
    • r+U

    "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

    • rb
    • wb
    • ab

    其他操作

    def close(self): # real signature unknown; restored from __doc__
            """
            Close the file.
            
            A closed file cannot be used for further I/O operations.  close() may be
            called more than once without error.
            """
            pass
    
        def fileno(self, *args, **kwargs): # real signature unknown
            """ Return the underlying file descriptor (an integer). """
            pass
    
        def isatty(self, *args, **kwargs): # real signature unknown
            """ True if the file is connected to a TTY device. """
            pass
    
        def read(self, size=-1): # known case of _io.FileIO.read
            """
            注意,不一定能全读回来
            Read at most size bytes, returned as bytes.
            
            Only makes one system call, so less data may be returned than requested.
            In non-blocking mode, returns None if no data is available.
            Return an empty bytes object at EOF.
            """
            return ""
    
        def readable(self, *args, **kwargs): # real signature unknown
            """ True if file was opened in a read mode. """
            pass
    
        def readall(self, *args, **kwargs): # real signature unknown
            """
            Read all data from the file, returned as bytes.
            
            In non-blocking mode, returns as much as is immediately available,
            or None if no data is available.  Return an empty bytes object at EOF.
            """
            pass
    
        def readinto(self): # real signature unknown; restored from __doc__
            """ Same as RawIOBase.readinto(). """
            pass #不要用,没人知道它是干嘛用的
    
        def seek(self, *args, **kwargs): # real signature unknown
            """
            Move to new file position and return the file position.
            
            Argument offset is a byte count.  Optional argument whence defaults to
            SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
            are SEEK_CUR or 1 (move relative to current position, positive or negative),
            and SEEK_END or 2 (move relative to end of file, usually negative, although
            many platforms allow seeking beyond the end of a file).
            
            Note that not all file objects are seekable.
            """
            pass
    
        def seekable(self, *args, **kwargs): # real signature unknown
            """ True if file supports random-access. """
            pass
    
        def tell(self, *args, **kwargs): # real signature unknown
            """
            Current file position.
            
            Can raise OSError for non seekable files.
            """
            pass
    
        def truncate(self, *args, **kwargs): # real signature unknown
            """
            Truncate the file to at most size bytes and return the truncated size.
            
            Size defaults to the current file position, as returned by tell().
            The current file position is changed to the value of size.
            """
            pass
    
        def writable(self, *args, **kwargs): # real signature unknown
            """ True if file was opened in a write mode. """
            pass
    
        def write(self, *args, **kwargs): # real signature unknown
            """
            Write bytes b to file, return number written.
            
            Only makes one system call, so not all of the data may be written.
            The number of bytes actually written is returned.  In non-blocking mode,
            returns None if the write would block.
            """
            pass

    例:文件的r w a

    data=open("yesterday",encoding="utf-8").read()  #文件句柄
    f=open("yesterday2",'r',encoding="utf-8")       #r读
    f=open("yesterday2",'w',encoding="utf-8")       #w写
    f=open("yesterday2",'a',encoding="utf-8")       #a追加 append
    print('-----------data2-------%s---------
    '%data2)
    print(data)
    f.write("
    when i was young ,i listen to the redio")
    data=f.read()
    print('read----',data)
     f.close()

     例2 读某个文件前五行

    f= open('yesterday','r',encoding="utf-8")
    for i in range(5):
              print(f.readlin())

     文件的读写:

    f=open("yesterday2",'r+',encoding="utf-8") #文件句柄 读写
    print(f.readline())
    print(f.readline())
    print(f.readline())
    print(f.tell()) #打印光标
    f.write("------------------------diao------------------------1
    ")
    f.write("------------------------diao------------------------2
    ")
    f.write("------------------------diao------------------------3
    ")
    print(f.readline())

    文件的写读:

    f=open("yesterday2",'w+',encoding="utf-8") #文件句柄 写读
    f.write("---------------diao---------------1
    ")
    f.write("---------------diao---------------2
    ")
    f.write("---------------diao---------------3
    ")
    f.write("---------------diao---------------4
    ")
    print(f.tell())                 #打印光标
    f.seek(10)                      #移动位置
    print(f.readline())
    f.write(“should ba at the beging of the  seconed line”)
    f.close()

    文件的追加写

    f=open("yesterday2",'a+',encoding="utf-8") #追加写

    二进制文件相关:

    f=open("yesterday2",'rb')  #读二进制文件
    print(f.readline())
    print(f.readline())
    print(f.readline())
    f=open("yesterday2",'wb')   #写二进制文件
    f.write("hello binary
    ".encode())
    f.close()

    循环文件:

    for line in f.readlines():
        print(line.strip())

    循环打印到第十行:

    简单:

    for index,line in enumerate(f.readlines()):
        if index == 9:
            print("------------我是分割线------------")
            continue
        print(line.strip())  #strip去掉空格

    高效:

    count = 0
    for line in f:
        if count ==9:
            print('---我是分割线')
            count +=1
            continue
        print(line)
        count +=1

     进度条:

    # -*- conding:utf-8 -*-
    _Author_ = "YoungCheung"
    import sys,time
    
    for n in range(1000):
        sys.stdout.write("...")
        sys.stdout.flush()
        time.sleep(1)

    文件的截取:

    f=open("yesterday2",'a',encoding="utf-8")
    f.seek(10)
    f.truncate(20)

    文件修改

    #!/usr/bin/python
    # -*- conding:utf-8 -*-
    _Author_ = "YoungCheung"
    
    f = open("yesterday2","r",encoding="utf-8")
    f_new = open("yesterday.bak","w",encoding="utf-8")
    
    for line in f:
        if "肆意的快乐等我享受" in  line:
            line = line.replace("肆意的快乐等我享受","肆意的快乐等zy去享受")
        f_new.write(line)
    f.close()
    f_new.close()

    with语句

    为了避免打开文件后忘记关闭,可以通过管理上下文,即:

    with open('log','r') as f:
        ...

    如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

    在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

    with open('log1') as obj1, open('log2') as obj2:
        pass

    2. 字符编码与转码

    详细文章:http://www.cnblogs.com/luotianshuai/articles/5735051.html 

     

    #打印系统默认编码:

    import sys
    print(sys.getdefaultencoding())

    #因为在Python3中默认就是unicode编码

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    #author youngcheung
    
    name = '张杨'
    #转为UTF-8编码
    print(name.encode('UTF-8'))
    #转为GBK编码
    print(name.encode('GBK'))
    #转为ASCII编码(报错为什么?因为ASCII码表中没有‘张杨’这个字符集~~)
    print(name.encode('ASCII'))

    #因为在python2.X中默认是ASCII编码,你在文件中指定编码为UTF-8,但是UTF-8如果你想转GBK的话是不能直接转的,的需要Unicode做一个转接站点。

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    #author youngcheung
    
    import chardet
    name = '你好'
    print chardet.detect(name)
    #先解码为Unicode编码,然后在从Unicode编码为GBK
    new_name = tim.decode('UTF-8').encode('GBK')
    print chardet.detect(new_name)
    
    #结果
    '''
    {'confidence': 0.75249999999999995, 'encoding': 'utf-8'}
    {'confidence': 0.35982121203616341, 'encoding': 'TIS-620'}
    '''

    函数及函数式编程

    1.函数的介绍

      函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。

      函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。

    2.定义一个函数

    你可以定义一个由自己想要功能的函数,以下是简单的规则:

    • 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()
    • 任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
    • 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
    • 函数内容以冒号起始,并且缩进。
    • return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。

     3.语法

    Python 定义函数使用 def 关键字,一般格式如下:

    def 函数名(参数列表):
        函数体

    默认情况下,参数值和参数名称是按函数声明中定义的的顺序匹配起来的。

    例:python中函数定义方法:

    def test(x):
        "The function definitions"
        x+=1
        return x
         
    def:定义函数的关键字
    test:函数名
    ():内可定义形参
    "":文档描述(非必要,但是强烈建议为你的函数添加描述信息)
    x+=1:泛指代码块或程序处理逻辑
    return:定义返回值

    补充:

       函数式编程就是:先定义一个数学函数,然后按照这个数学模型用编程语言去实现它。至于具体如何实现和这么做的好处,后续我会详细介绍。

    面向过程和定义函数:

    #!/usr/bin/python
    # -*- conding:utf-8 -*-
    _Author_ = "YoungCheung"
    #函数
    def function1():
        """test1"""
        print('in the function1')
        return 0
    #过程
    def function2():
        """test2"""
        print('in the function2')
    x=function1()
    y=function2()
    print('from function1 %s' %x)
    print('from function1 %s' %y)

    输出结果:

    in the function1
    in the function2
    from function1 0
    from function1 None
    View Code

    4.为什么要使用函数

    假设我们编写好了一个逻辑(功能),用来以追加的方式写日志:
    with open('a.txt','ab') as f:
        f.write('end action')
    现在有三个函数,每个函数在处理完自己的逻辑后,都需要使用上面这个逻辑,那么唯一的方法
    就是,拷贝三次这段逻辑
    def test1():
        print 'test1 starting action...'
         
        with open('a.txt','a+') as f:
            f.write('end action')
         
    def test2():
        print 'test2 starting action...'
         
        with open('a.txt','a+') as f:
            f.write('end action')
          
    def test3():
        print 'test3 starting action...'
     
        with open('a.txt','a+') as f:
            f.write('end action')

     那么假设有>N个函数都需要使用这段逻辑,你可以拷贝N次吗?

    优化后的代码:

    def logger():
        with open('a.txt','a+') as f:
            f.write('end action
    ')
    
    def test1():
        print("test1 starting action")
        logger()
    
    def test2():
        print("test2 starting action")
        logger()
    
    def test3():
        print("test3 starting action")
        logger()

    需求变了(让我们来为日志加上时间吧)

    def logger():
        time_format = '%Y-%m-%d %X'
        time_current = time.strftime(time_format)
        with open('a.txt','a+') as f:
            f.write('%s end action
    ' %time_current)
    
    def test1():
        print("test1 starting action")
        logger()
    
    def test2():
        print("test2 starting action")
        logger()
    
    def test3():
        print("test3 starting action")
        logger()

    总结例二和例三可概括使用函数的三大优点

    1.代码重用

    2.保持一致性

    3.可扩展性

    5.函数和过程:

    过程定义:过程就是简单特殊没有返回值的函数

    这么看来我们在讨论为何使用函数的的时候引入的函数,都没有返回值,没有返回值就是过程,没错,但是在python中有比较神奇的事情

    #!/usr/bin/python
    # -*- conding:utf-8 -*-
    __Author__ = "YoungCheung"
    def test01():
        msg='hello The little green frog'
        print(msg)
    def test02():
        msg='hello youngcheung'
        print(msg)
        return msg
    t1=test01()
    t2=test02()
    print('from test01 return is [%s]' %t1)
    print('from test01 return is [%s]' %t2)

    6.函数的返回值

    #!/usr/bin/python
    # -*- conding:utf-8 -*-
    _Author_ = "YoungCheung"
    
    def test1():
        pass
    def test2():
        return 0
    def test3():
        return 1,'hello',['a','b','c'],{'name':'alex'}
    x=test1()
    y=test2()
    z=test3()
    print(x)
    print(y)
    print(z)

    输出结果:

    None
    0
    (1, 'hello', ['a', 'b', 'c'], {'name': 'alex'})
    View Code

    总结:

       返回值数=0:返回None

       返回值数=1:返回object

       返回值数>1:返回tuple

    7.函数的调用

    定义一个函数:给了函数一个名称,指定了函数里包含的参数,和代码块结构。

    这个函数的基本结构完成以后,你可以通过另一个函数调用执行,也可以直接从 Python 命令提示符执行。

    如下实例调用了printme()函数:

    !/usr/bin/python3
     
    # 定义函数
    def printme( str ):
       "打印任何传入的字符串"
       print (str);
       return;
     
    # 调用函数
    printme("我要调用用户自定义函数!");
    printme("再次调用同一函数");

    输出结果:

    我要调用用户自定义函数!
    再次调用同一函数

    调用方法:

    1.test()执行,()表示调用函数test,()内可以有参数也可没有

    参数:

    1.形参和实参

    形参:形式参数,不是实际存在,是虚拟变量。在定义函数和函数体的时候使用形参,目的是在函数调用时接收实参(实参个数,类型应与实参一一对应)

    实参:实际参数,调用函数时传给函数的参数,可以是常量,变量,表达式,函数,传给形参       

    区别:形参是虚拟的,不占用内存空间,.形参变量只有在被调用时才分配内存单元,实参是一个变量,占用内存空间,数据传送单向,实参传给形参,不能形参传给

    2.位置参数和关键字(标准调用:实参与形参位置一一对应;关键字调用:位置无需固定)

    3.默认参数

    4.参数组

    #!/usr/bin/python
    # -*- conding:utf-8 -*-
    __Author__ = "YoungCheung"
    def test(x,y,z):
        print(x)
        print(y)
        print(z)
    test(1,2,3)       #把1 2赋值给test的x y,与形参一一对应
    test(y=1,x=2,z=3) #直接赋值传给函数,与形参顺序无关
    test(3,y=2,z=4)   #位置参数优先
    test(3,z=2,y=4)

     8.按值传递参数和按引用传递参数

    在 Python 中,所有参数(变量)都是按引用传递。如果你在函数里修改了参数,那么在调用这个函数的函数里,原始的参数也被改变了。例如:

    #!/usr/bin/python3
     
    # 可写函数说明
    def changeme( mylist ):
       "修改传入的列表"
       mylist.append([1,2,3,4]);
       print ("函数内取值: ", mylist)
       return
     
    # 调用changeme函数
    mylist = [10,20,30];
    changeme( mylist );
    print ("函数外取值: ", mylist)

    传入函数的和在末尾添加新内容的对象用的是同一个引用。故输出结果如下:

    函数内取值:  [10, 20, 30, [1, 2, 3, 4]]
    函数外取值:  [10, 20, 30, [1, 2, 3, 4]]

    9.参数

    以下是调用函数时可使用的正式参数类型:

    • 必需参数(位置参数)
    • 关键字参数
    • 默认参数
    • 不定长参数

    9.1必须参数

    必需参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。

    调用printme()函数,你必须传入一个参数,不然会出现语法错误:

    #!/usr/bin/python3
     
    #可写函数说明
    def printme( str ):
       "打印任何传入的字符串"
       print (str);
       return;
     
    #调用printme函数
    printme();

    输出结果:

    Traceback (most recent call last):
      File "test.py", line 10, in <module>
        printme();
    TypeError: printme() missing 1 required positional argument: 'str'

    9.2关键字参数

    关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。

    使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。

    以下实例在函数 printme() 调用时使用参数名:

    #!/usr/bin/python3
     
    #可写函数说明
    def printme( str ):
       "打印任何传入的字符串"
       print (str);
       return;
     
    #调用printme函数
    printme( str = "youngcheung");

    输出结果:

    youngcheung

    以下实例中演示了函数参数的使用不需要使用指定顺序:

    #!/usr/bin/python3
     
    #可写函数说明
    def printinfo( name, age ):
       "打印任何传入的字符串"
       print ("名字: ", name);
       print ("年龄: ", age);
       return;
     
    #调用printinfo函数
    printinfo( age=21, name="YoungCheung" );

    输出结果:

    姓名:YoungCheung
    年龄:21

    9.3默认参数

    调用函数时,如果没有传递参数,则会使用默认参数。以下实例中如果没有传入 age 参数,则使用默认值:

    #!/usr/bin/python3
     
    #可写函数说明
    def printinfo( name, age = 21):
       "打印任何传入的字符串"
       print ("名字: ", name);
       print ("年龄: ", age);
       return;
     
    #调用printinfo函数
    printinfo( age=21, name=YoungCheung" );
    print ("------------------------")
    printinfo( name="zhangyang" );

    输出结果:

    名字:  YoungCheung
    年龄:  21
    ------------------------
    名字:  zhangyang
    年龄:  21

     9.4 不定长参数

    你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数,和上述2种参数不同,声明时不会命名。基本语法如下:

    def functionname([formal_args,] *var_args_tuple ):
       "函数_文档字符串"
       function_suite
       return [expression]

    加了星号(*)的变量名会存放所有未命名的变量参数。如果在函数调用时没有指定参数,它就是一个空元组。我们也可以不向函数传递未命名的变量。如下实例:

    #!/usr/bin/python3
     
    # 可写函数说明
    def printinfo( arg1, *vartuple ):
       "打印任何传入的参数"
       print ("输出: ")
       print (arg1)
    for var in vartuple: print (var) return; # 调用printinfo 函数 printinfo( 10 );
    #printinfo(*[1,2,3,4,5,]) or args=tuple([1,2,3,4,5]) printinfo(
    70, 60, 50 );

    输出结果:

    输出:
    10
    输出:
    70
    60
    50

    接受字典**kwargs :把 N个关键字参数,转换成字典的方式

    def test(**kwargs):
            print(kwargs)
    
    test(name='alex',age=8, sex='N')

    输出结果:

    {'name': 'alex', 'sex': 'N', 'age': 8}

    复杂:

    def test1(name,age=21,**kwargs):
        print(name)
        print(age)
        print(kwargs)
    test1('zhangyang',sex='N',hobby='tesla') #age可以写可以不写,
    
    test1('zhangyang',age='21',sex='N',hobby='tesla') #age可以写可以不写,

    输出结果:

    zhangyang
    21
    {'sex': 'N', 'hobby': 'tesla'}
    zhangyang
    21
    {'sex': 'N', 'hobby': 'tesla'}

    10.前向引用

    函数action体内嵌套某一函数logger,该logger的声明必须早于action函数的调用,否则报错

       print 'in the action'
        logger()
    action()
    报错NameError: global name 'logger' is not defined
    def logger():
        print 'in the logger'
    def action():
        print 'in the action'
        logger()
     
    action()
     
     
     
    def action():
        print 'in the action'
        logger()
    def logger():
        print 'in the logger'
     
    action()

    11.return语句

    return [表达式] 语句用于退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None。之前的例子都没有示范如何返回数值,以下实例演示了 return 语句的用法:

    #!/usr/bin/python3
    
    # 可写函数说明
    def sum( arg1, arg2 ):
       # 返回2个参数的和."
       total = arg1 + arg2
       print ("函数内 : ", total)
       return total;
    
    # 调用sum函数
    total = sum( 10, 20 );
    print ("函数外 : ", total)
    输出结果:
    函数内 :  30
    函数外 :  30

    12.变量作用域

    Pyhton 中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在哪里赋值的。

    变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。两种最基本的变量作用域如下:

    • 全局变量
    • 局部变量

    全局变量和局部变量

    在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量
    全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
    当全局变量与局部变量同名时:在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。

    定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。

    局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。如下实例:

    #!/usr/bin/python3
    
    total = 0; # 这是一个全局变量
    # 可写函数说明
    def sum( arg1, arg2 ):
        #返回2个参数的和."
        total = arg1 + arg2; # total在这里是局部变量.
        print ("函数内是局部变量 : ", total)
        return total;
    
    #调用sum函数
    sum( 10, 20 );
    print ("函数外是全局变量 : ", total)

    输出结果

    函数内是局部变量 :  30
    函数外是全局变量 :  0

    例:

    def change_name(name):
        print("before change",name)
        name='Alex ' #这个函数就是这个函数的作用域
        # age=23
        print("after change",name)
    
    name = 'alex'
    change_name(name)
    print(name)

    输出结果:

    before change alex
    after change Alex 
    alex

    13.递归函数

    在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。

    #!/usr/bin/python
    # -*- conding:utf-8 -*-
    _Author_ = "YoungCheung"
    
    def calc(n):
        print(n)
        if int(n/2)  >0:
            return calc( int(n/2))
        print("-->",n)
    calc(10)

    输出结果

    10
    5
    2
    1
    --> 1

    递归特性:

    1. 必须有一个明确的结束条件

    2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少

    3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

    14.匿名函数

    python 使用 lambda 来创建匿名函数。

    所谓匿名,意即不再使用 def 语句这样标准的形式定义一个函数。

    • lambda 只是一个表达式,函数体比 def 简单很多。
    • lambda的主体是一个表达式,而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。
    • lambda 函数拥有自己的命名空间,且不能访问自有参数列表之外或全局命名空间里的参数。
    • 虽然lambda函数看起来只能写一行,却不等同于C或C++的内联函数,后者的目的是调用小函数时不占用栈内存从而增加运行效率。

    语法

    lambda 函数的语法只包含一个语句,如下:

    lambda [arg1 [,arg2,.....argn]]:expression
    例:
    #!/usr/bin/python3
     
    # 可写函数说明
    sum = lambda arg1, arg2: arg1 + arg2;
     
    # 调用sum函数
    print ("相加后的值为 : ", sum( 10, 20 ))
    print ("相加后的值为 : ", sum( 20, 20 ))
    输出结果:
    相加后的值为 :  30
    相加后的值为 :  40

    15.函数编程式介绍

    函数是Python内建支持的一种封装,我们通过把大段代码拆成函数,通过一层一层的函数调用,就可以把复杂任务分解成简单的任务,这种分解可以称之为面向过程的程序设计。函数就是面向过程的程序设计的基本单元。
    而函数式编程(请注意多了一个“式”字)——Functional Programming,虽然也可以归结到面向过程的程序设计,但其思想更接近数学计算。
    我们首先要搞明白计算机(Computer)和计算(Compute)的概念。
    在计算机的层次上,CPU执行的是加减乘除的指令代码,以及各种条件判断和跳转指令,所以,汇编语言是最贴近计算机的语言。
    而计算则指数学意义上的计算,越是抽象的计算,离计算机硬件越远。
    对应到编程语言,就是越低级的语言,越贴近计算机,抽象程度低,执行效率高,比如C语言;越高级的语言,越贴近计算,抽象程度高,执行效率低,比如Lisp语言。
    函数式编程就是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数我们称之为没有副作用。而允许使用变量的程序设计语言,由于函数内部的变量状态不确定,同样的输入,可能得到不同的输出,因此,这种函数是有副作用的。
    函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数!
    Python对函数式编程提供部分支持。由于Python允许使用变量,因此,Python不是纯函数式编程语言。

    一、定义

    简单说,"函数式编程"是一种"编程范式"(programming paradigm),也就是如何编写程序的方法论。

    主要思想是把运算过程尽量写成一系列嵌套的函数调用。举例来说,现在有这样一个数学表达式:

     (1 + 2) * 3 - 4

    传统的过程式编程,可能这样写:

      var a = 1 + 2;
    
      var b = a * 3;
    
      var c = b - 4;

    函数式编程要求使用函数,我们可以把运算过程定义为不同的函数,然后写成下面这样:

    var result = subtract(multiply(add(1,2), 3), 4);

    这就是函数式编程。

    16.高阶函数

    变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

    def add(x,y,f):
        return f(x) + f(y)
      
    res = add(3,-6,abs)
    print(res)

    输出结果

     9

    程序练习  

    程序1: 实现简单的shell sed替换功能

    程序2:修改haproxy配置文件 

    详细文章:http://www.cnblogs.com/luotianshuai/articles/5735051.html 

    1、查
        输入:www.oldboy.org
        获取当前backend下的所有记录
    
    2、新建
        输入:
            arg = {
                'bakend': 'www.oldboy.org',
                'record':{
                    'server': '100.1.7.9',
                    'weight': 20,
                    'maxconn': 30
                }
            }
    
    3、删除
        输入:
            arg = {
                'bakend': 'www.oldboy.org',
                'record':{
                    'server': '100.1.7.9',
                    'weight': 20,
                    'maxconn': 30
                }
            }
    
    需求
    需求
    global       
            log 127.0.0.1 local2
            daemon
            maxconn 256
            log 127.0.0.1 local2 info
    defaults
            log global
            mode http
            timeout connect 5000ms
            timeout client 50000ms
            timeout server 50000ms
            option  dontlognull
    
    listen stats :8888
            stats enable
            stats uri       /admin
            stats auth      admin:1234
    
    frontend oldboy.org
            bind 0.0.0.0:80
            option httplog
            option httpclose
            option  forwardfor
            log global
            acl www hdr_reg(host) -i www.oldboy.org
            use_backend www.oldboy.org if www
    
    backend www.oldboy.org
            server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
    原配置文件

    .

  • 相关阅读:
    Linux系统运维之MYSQL数据库集群部署(主从复制)
    Linux系统运维之负载均衡Tengine
    Linux系统运维之subversionEdge部署
    Linux系统运维之Hadoop、Hive、Flume数据处理
    CoIDE在STM32系列单片机中的使用实践
    软硬件调试九法:第三条规则 不要想而要看
    《产品经理》读书笔记
    <读书笔记> 代码整洁之道
    关于鼠标手的症状和恢复方法
    <读书笔记>软件调试之道 :从大局看调试-理想的调试环境
  • 原文地址:https://www.cnblogs.com/youngcheung/p/5756347.html
Copyright © 2020-2023  润新知