美文网首页程序员我的Python自学之路
给深度学习入门者的Python快速教程 - 基础篇 - 笔记

给深度学习入门者的Python快速教程 - 基础篇 - 笔记

作者: rabbitq0082 | 来源:发表于2017-03-17 17:06 被阅读261次

    标签: 读书笔记 python 深度学习

    原文链接

    1. Class

    • 类的基本声明和成员
    class Person:
        '''Test class'''
        def __init__(self, name):
            self.name = name
            self._name = name
            self.__inner_name = 'Alexanda.' + name
            
        def intro(self):
            print('Hi, I am', self._name)
    
        def greeting(self):
            print('I am', self.name, ', What''s up.')
    
        def _protected_greeting(self):
            print('I am', self._name, ', What''s up.')
            
        def __private_greeting(self):
            print('I am', self.__inner_name, ', What''s up. I do not give a shit on you!')
        
        def what_i_think(self):
            self.__private_greeting()
    
    #生成类的实例:对象
    JONSON = Person('Jonson')
    
    #打印对象和类的说明文档
    print('Object class doc:', JONSON.__doc__)
    print('Class class doc:', Person.__doc__)
    
    #访问变量
    print(JONSON.name)  #普通变量:public变量,可以正常访问
    print(JONSON._name)  #单下划线变量:protected变量,可以正常访问
    #print(JONSON.__inner_name)  #报错,双下划线变量:private变量,不可直接访问
    
    #调用方法
    JONSON.intro()  #对象的普通方法:public方法
    JONSON.greeting()
    JONSON._protected_greeting()  #单下划线方法:protected方法,可以正常访问
    #JONSON.__private_greeting()  #报错,双下划线方法:private方法,不可直接访问
    JONSON.what_i_think()  #通过普通方法间接调用private方法
    
    Object class doc: Test class
    Class class doc: Test class
    Jonson
    Jonson
    Hi, I am Jonson
    I am Jonson , Whats up.
    I am Jonson , Whats up.
    I am Alexanda.Jonson , Whats up. I do not give a shit on you!
    
    • 类的继承
    class Student(Person):
        '''Student inherit from Person'''
        def greeting(self):
            super().greeting()  #调用父类的方法
            print('I am a student.')
            
    TOM = Student('Tom')
    TOM.greeting()
    
    I am Tom , Whats up.
    I am a student.
    

    2. 函数式编程 map, reduce和filter

    • map:对可遍历结构的每个元素执行同样的操作
    print(list(map(lambda x: x - 1, [1, 2, 3])))  #[1-1, 2-1, 3-1]
    
    #多参数的操作(函数或者匿名lambda函数),将从map的多个可遍历参数中获取对应的元素执行操作
    print(list(map(lambda x, y: x + y, [1, 2, 3], [4, 5, 6])))  #[1+4, 2+5, 3+6]
    print(list(map(lambda x, y: x + y, [1, 2, 3], [4, 5])))  #[1+4, 2+5]
    
    [0, 1, 2]
    [5, 7, 9]
    [5, 7]
    
    • reduce:对可遍历结构的元素按顺序进行两个输入参数的操作,并且每次操作的结果作为下次操作的第一个输入参数,还未遍历的元素作为第二个输入参数。这样就会把一个可遍历的一系列元素,减少(reduce)成为一个元素。
    from functools import reduce
    print(reduce(lambda x, y: x + y, [1, 2, 3]))  # (1 + 2) + 3 = 6
    
    6
    
    • filter:对可遍历结构的元素,基于某一测试操作过滤出一些元素
    print(list(filter(lambda x: x > 0, [-5, -3, 1, 0, -11, 10])))
    
    [1, 10]
    

    3. 列表推导(list comprehension)

    根据条件表达式,迭代列表的各个元素,通过指定的操作生成新的序列对象

    Lst_1 = [1, 2, 3]
    Lst_2 = [x*x for x in Lst_1]
    Lst_3 = [x*x for x in Lst_1 if x < 3]
    
    print(Lst_2)
    print(Lst_3)
    
    Dic_1 = {x: x*x for x in Lst_1}
    
    print(Dic_1)
    
    [1, 4, 9]
    [1, 4]
    {1: 1, 2: 4, 3: 9}
    

    4. 字符串

    • 字符串基本操作
    Str_1 = 'Life is short, you need Python -- Bruce Eckle'
    print(Str_1.lower())
    print(Str_1.upper())
    print("'i' count in Str_1:", Str_1.count('i'))
    print("'e' position in Str_1:", Str_1.find('e'))
    print("'need' reverse position in Str1:", Str_1.rfind('need'))
    print('Replace you with I:', Str_1.replace('you', 'I'))
    Str_Items = Str_1.split(sep = ' ')  #sep默认值即空格,此处参数可省略
    print("Str_1 elements by seperator ' ':", Str_Items)
    Str_Resume = ' '.join(Str_Items)
    print("Resumed String with elements of Str_1:", Str_Resume)
    
    life is short, you need python -- bruce eckle
    LIFE IS SHORT, YOU NEED PYTHON -- BRUCE ECKLE
    'i' count in Str_1: 2
    'e' position in Str_1: 3
    'need' reverse position in Str1: 19
    Replace you with I: Life is short, I need Python -- Bruce Eckle
    Str_1 elements by seperator ' ': ['Life', 'is', 'short,', 'you', 'need', 'Python', '--', 'Bruce', 'Eckle']
    Resumed String with elements of Str_1: Life is short, you need Python -- Bruce Eckle
    
    • 利用format函数对字符串进行格式化 详细文档
    #按顺序格式化字符串
    Str_1 = 'I prefer {} rather than {}.'
    print(Str_1.format('playing Basketball', 'swimming'))
    
    #在大括号中指定参数所在位置
    Str_1 = 'I prefer {1} {0} to {2} {0}.'
    print(Str_1.format('food', 'Chinese', 'U.S'))
    
    #在大括号中指定参数的名字
    Str_1 = '{name} is {age} years old.'
    print(Str_1.format(age=3, name='Terry'))
    
    I prefer playing Basketball rather than swimming.
    I prefer Chinese food to U.S food.
    Terry is 3 years old.
    

    5. 文件操作和pickle

    • 从IO资源管理安全性考虑,使用上下文管理器(with-as)来打开文件

      1. 假设存在文件name_age.txt如下:
      Tom,8
      Jerry,7
      Terry,3
      
      1. 读取文件内容按行格式化显示:
      with open('name_age.txt', 'r') as f:  #打开文件,读取模式
          lines = f.readlines()  #一次读取所有行
          for line in lines:  #按行格式化并显示信息
              name, age = line.rstrip().split(',')
              print('{} is {} years old.'.format(name, age))
      
      1. 如果需要将名字和年龄的顺序交换,保存成新的文件age_name.txt:
      with open('name_age.txt', 't') as fread, open('age_name.txt', 'w') as fwrite:
          line = fread.readline()  #首先读取一行
          while line:  #循环所有读取的行
              name, ag = line.rstrip().split(',')
              fwrite.write('{}, {}\n'.formate(age, name))  #写入新文件
              line = fread.readline()  #读取下一行
      
    • 将对象序列化保存,需要时再反序列化读取

    import pickle
    
    lines = ['Hello HanMeiMei', 'Hello LiLei', 'How are you', 'Fine, thank you, And you?']
    
    with open('d:/lines.pkl', 'wb') as f:  #序列化对象,保存到文件中
        pickle.dump(lines, f)
        
    with open('d:/lines.pkl', 'rb') as f:  #从文件读取并反序列化
        lines_back = pickle.load(f)
        
    print(lines_back)
    
    ['Hello HanMeiMei', 'Hello LiLei', 'How are you', 'Fine, thank you, And you?']
    

    相关文章

      网友评论

        本文标题:给深度学习入门者的Python快速教程 - 基础篇 - 笔记

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