数据分析:Python之进阶篇

文章目录

    • [第四章 常见的数据结构](#第四章 常见的数据结构)
      • [4.1 列表](#4.1 列表)
      • [4.2 元组](#4.2 元组)
      • [4.3 字典](#4.3 字典)
      • [4.4 集合](#4.4 集合)
    • [第五章 函数与python库的使用](#第五章 函数与python库的使用)
      • [5.1 函数](#5.1 函数)
      • [5.2 Python中的库](#5.2 Python中的库)
    • [第六章 文件操作、序列化与反序列化](#第六章 文件操作、序列化与反序列化)
      • [6.1 文件操作](#6.1 文件操作)
      • [6.2 序列化和反序列化](#6.2 序列化和反序列化)
    • [第七章 面向对象和异常处理](#第七章 面向对象和异常处理)
      • [7.1 面向对象](#7.1 面向对象)
      • [7.2 异常处理](#7.2 异常处理)

第四章 常见的数据结构

4.1 列表

  1. 列表(list)

    • 列表的元素都是有序的

    • 列表中每个元素都是可变的

    • 列表可以容纳Python中任何对象

    python 复制代码
    ["a","b",1,2]
  2. 列表的创建

    python 复制代码
    a = [1,2,3,4]  ##推荐这种方法
    print(a)
    python 复制代码
    #b = []
    b = list()  ##创建一个空列表
    python 复制代码
    b.append(1)  ## append是列表的方法,表示在后面追加元素
    b.append(2)
    b.append(3)
    b.append(4)
    print(b)
  3. 列表的索引和切片

    python 复制代码
    ## 索引
    a = [1,2,3,4]
    print(a[0])  ##下标是0开始
    print(a[-1]) ##-1下标表示最后一个
    python 复制代码
    ## 切片[start:end]
    a = [1,2,3,4]
    print(a[0:3]) ##1,2,3
    print(a[:3])  ##start如果为0可以省略
    print(a[1:4]) ##2,3,4
    print(a[:])   ##end如果为最后一个,也可以省略
  4. 列表修改、删除、拼接、遍历

    python 复制代码
    ## 修改
    a = [1,2,3,4]
    a[1] = 5  ##把值赋给索引就可以
    print(a)  ##[1, 5, 3, 4]
    a[-1] = 10
    print(a)  ##[1, 5, 3, 10]
    python 复制代码
    ## 删除
    a = [1,5,3,10]
    del a[1] ##del加索引就可以,delete
    del a[-1]
    print(a)  ##[1, 3]
    python 复制代码
    ## 拼接
    a = [1,3]
    b = [2,4]
    print(a + b)  ##[1, 3, 2, 4]
    print(a + b + [5,6])  ##[1, 3, 2, 4, 5, 6]
    python 复制代码
    ## 是否在列表中,遍历
    a = [1,3]
    if 1 in a:
        print("存在")
    else:
        print("不存在")
        
    for i in a:
        print(i)
列表的进阶用法
  1. 多维列表

    python 复制代码
    a = [1,2,3,4]  ##看成一排数字
    python 复制代码
    b = [[1,2],[3,4]]  ##二维列表
    print(b)  ##[[1, 2], [3, 4]]
    python 复制代码
    c = [[[1], [2]], [[3], [4]], [[5], [6]]]  ##三维列表
    python 复制代码
    print(a[0])     ##1
    print(b[0][0])  ##1
    print(b[0][1])  ##2
    
    print(c[0][0][0])##1
    print(c[0][1][0])##2
    print(c[1][0][0])##3
    print(c[2][1][0])##6  ##多少维度,对应多少个方括号
  2. 求列表的长度

    python 复制代码
    ## 求列表长度
    a = [1,2,3,4]
    b = [[1,2],[3,4]]
    c = [[[1], [2]], [[3], [4]], [[5], [6]]]
    print(len(a))  ##4
    print(len(b))  ##2
    print(len(c[0][0])) ##1
  3. 列表的方法调用(append,count,extend,sort...)

    python 复制代码
    a = [1,2,3,4]
    • append
    python 复制代码
    ## append 表示追加
    a.append(5)
    print(a)  ##[1, 2, 3, 4, 5]
    • count
    python 复制代码
    ## count 统计有多少个
    print(a.count(6))  ##0
    print(a.count(4))  ##1
    • extend
    python 复制代码
    ## extend 实时更新a中元素,没有返回值
    a.extend([6,7,8])
    print(a)  ##[1, 2, 3, 4, 5, 6, 7, 8]执行一遍
    • index
    python 复制代码
    ## index  ##返回下标,没有就会报错
    print(a.index(6)) ##5
    • insert
    python 复制代码
    ## insert
    a.insert(0,8)
    python 复制代码
    print(a)  ##[8, 1, 2, 3, 4, 5, 6, 7, 8]
    print(len(a))  ##9
    python 复制代码
    a.insert(2,10)
    python 复制代码
    print(a)  ##[8, 1, 10, 2, 3, 4, 5, 6, 7, 8]
    print(len(a))  ##10
    • pop
    python 复制代码
    ## pop 弹出最后的元素,列表会更新
    d = a.pop()
    python 复制代码
    print(len(a))  ##9
    print(d)   ##8
    • remove
    python 复制代码
    a = [8, 1, 10, 2, 3, 4, 5, 6, 7,8]
    python 复制代码
    a.remove(8)  ##remove只删除匹配到的第一个
    python 复制代码
    print(a)  ##[1, 10, 2, 3, 4, 5, 6, 7, 8]
    • reverse、sort
    python 复制代码
    #逆序
    a.reverse()
    print(a)  ##[8, 7, 6, 5, 4, 3, 2, 10, 1]
    python 复制代码
    #排序 ##默认从小到大排序
    a.sort()  ##a.sort(reverse=False)
    print(a)  ##[1, 2, 3, 4, 5, 6, 7, 8, 10]
    ##从大到小排序
    a.sort(reverse=True)
    print(a)  ##[10, 8, 7, 6, 5, 4, 3, 2, 1]
    • clear
    python 复制代码
    a.clear()
    print(a)  ##[]
    • extend
    python 复制代码
    a.extend([1,2,3,4])
    python 复制代码
    print(a)
    • copy
    python 复制代码
    a = [1,2,3,4] 
    e = a.copy  ##copy跟赋值的区别,copy赋值得到新的列表
    python 复制代码
    f = a
    python 复制代码
    id(e)  ##2313461048480
    python 复制代码
    id(f)  ##2313460995328
    python 复制代码
    g = a
    python 复制代码
    id(g) ##2313460995328

4.2 元组

  1. 元组(tuple)

    • 元组与列表类似,但元组中的元素不能修改

      python 复制代码
      ("lisi",24,1.75)
  2. 元组的创建

    python 复制代码
    a = ("abc",1)
    type(a) ##查看数据类型,即tuple
    python 复制代码
    b = ["abc",1]
    type(b)  ##list
    b = tuple(b)  ##把列表转换为元组
    type(b)  ##tuple
  3. 元组的索引和切片

    python 复制代码
    ## 索引和切片
    a = ("abc",1) 
    print(a[0])  ##索引下标也是从0开始  abc
    print(a[:2]) ##('abc', 1)
  4. 元组的求长度、删除、拼接、遍历

    python 复制代码
    ## 求长度
    a = ("abc",1) 
    c = (1,2,3)
    print(len(a))  ##2
    print(len(c))  ##3
    python 复制代码
    ## 删除。元组使用del只能删掉整个元素,不能删掉单个元素
    a = ("abc",1) 
    print(a)
    del a
    print(a)  ##name 'a' is not defined
    python 复制代码
    ## 拼接
    a = ("abc",1) 
    b = ("bcd",2)
    print(id(a))  ##2313443422720
    print(id(b))  ##2313444252544
    print(a + b)  ##('abc', 1, 'bcd', 2)
    print(id(a+b))  ##2313461069760
    python 复制代码
    ## 判断元素是否在列表中
    a = ("abc",1) 
    "bcd" in a  ##False
    
    ##遍历
    for i in a:
        print(i)  ##abc 1

4.3 字典

  1. 字典(dict)

    • 简单地说,字典就是存储键值对的数据结构

    • 字典中的数据必须是以键值对的形式存在的

    • 字典中键(key)是不能重复,也不能修改;而值(value)是可重复,可修改的,可以是任何对象

    python 复制代码
    {"a":1,"b":2,1:2}
  2. 字典的创建

    python 复制代码
    info = {"age":26,"heght":167,"BWH":(89,62,92),"interest":["看书","美食"]}
    python 复制代码
    type(info) ##dict
    infos = {"小美":{"age":26,"heght":167,"BWH":(89,62,92),"interest":["看书","美食"]}}
    python 复制代码
    infos["小花"] = {"age":25,"heght":163,"BWH":(85,60,90),"interest":["唱歌","健身"]}
    python 复制代码
    infos["小红"] = {"age":24,"heght":160,"BWH":(80,59,84),"interest":["旅行"]}
    infos["小甜甜"] = {"age":24,"heght":161,"BWH":(84,60,89),"interest":["看电影","健身"]}
  3. 字典的索引和查询

    python 复制代码
    ## 查询
    infos["小甜甜"]["BWH"]  ##通过[key]来索引查找    (84, 60, 89)
    python 复制代码
    infos.get("小鱼",{})  ##get的第二个参数是查看key不存在的时候返回的值  {}
  4. 字典的修改、添加、删除元素

    python 复制代码
    ## 修改
    infos["小花"]["height"] = 165  ##索引再加附加操作进行修改
    infos["小花"]["height"] ##165
    python 复制代码
    ## 添加元素
    infos["小花"] = {"age":25,"heght":163,"BWH":(85,60,90),"interest":["唱歌","健身"]}
    print(infos)  ##{'小美': {'age': 26, 'heght': 167, 'BWH': (89, 62, 92), 'interest': ['看书', '美食']}, '小花': {'age': 25, 'heght': 163, 'BWH': (85, 60, 90), 'interest': ['唱歌', '健身']}}
    
    infos["小红"] = {"age":24,"heght":160,"BWH":(80,59,84),"interest":["旅行"]}
    infos["小甜甜"] = {"age":24,"heght":161,"BWH":(84,60,89),"interest":["看电影","健身"]}
    python 复制代码
    ##删除
    del infos["小甜甜"]
  5. 求字典的长度

    python 复制代码
    ## len求长度
    print(len(infos))
  6. 字典的遍历

    python 复制代码
    ## 字典的遍历。keys返回字典所有的键/key
    infos.keys() ##dict_keys(['小美', '小花', '小红', '小甜甜'])
    #type(infos.keys())  ##dict_keys
    list(infos.keys())  ##['小美', '小花', '小红', '小甜甜']  先转换为列表
    python 复制代码
    a = list(infos.keys()) ##keys返回字典所有的键/key
    for i in a:
        print("key={},value={}".format(i,infos[i]))
    python 复制代码
    ##结果
    key=小美,value={'age': 26, 'heght': 167, 'BWH': (89, 62, 92), 'interest': ['看书', '美食']}
    key=小花,value={'age': 25, 'heght': 163, 'BWH': (85, 60, 90), 'interest': ['唱歌', '健身'], 'height': 165}
    key=小红,value={'age': 24, 'heght': 160, 'BWH': (80, 59, 84), 'interest': ['旅行']}
    key=小甜甜,value={'age': 24, 'heght': 161, 'BWH': (84, 60, 89), 'interest': ['看电影', '健身']}
    python 复制代码
    for i in list(infos.items()):  ##items返回所有由key和value所构成的元组
        print("key={},value={}".format(i[0],i[1]))

4.4 集合

  1. 集合(set)

    • 简单地说,集合就是无序的不重复元素序列
    • 集合中的元素不可重复
    • 集合中的元素是无序的,所以没有索引
    • basket = {'apple','orange','pear','banana'}
  2. 集合的创建

    python 复制代码
    a = {1,2,3}
    type(a) ##set就是Python中集合的数据类型
    python 复制代码
    b = {}  ##表示空集合不能用空的花括号
    type(b) ##dict
    python 复制代码
    b = set() ##表示空的集合
    type(b)  ##set
    python 复制代码
    ## 转换
    a = [1, 2, 3]
    type(a)  ##list
    python 复制代码
    a = set(a) ## 通过set把列表转换为集合
    type(a)  ##set
    • 实践(去重,交集、并集)

      python 复制代码
      user_id_list = [1, 2, 3, 4, 4, 5, 5]
      len(user_id_list)  ##7
      python 复制代码
      ## 去重
      user_id_set = set(user_id_list)
      ## len求集合长度
      len(user_id_set)  ##5
      python 复制代码
      ## 求交集
      user_id_list = [1, 2, 3, 4, 4, 5, 5]
      user_id_list2 = [2, 3, 7, 8, 9]
      
      user_id_set = set(user_id_list)
      user_id_set2 = set(user_id_list2)
      
      print(user_id_set)  ##{1, 2, 3, 4, 5}
      print(user_id_set2) ##{2, 3, 7, 8, 9}
      python 复制代码
      user_id_set & user_id_set2 ## &可以求交集 
      ##即{2, 3}
      python 复制代码
      user_id_set.intersection(user_id_set2) ## intersection表示求交集的方法,传入需要运算的另外一个集合 
      ##即{2, 3}
      python 复制代码
      ## 求并集
      user_id_set | user_id_set2 ## |可以求并集
      python 复制代码
      user_id_set.union(user_id_set2) ## union表示求并集的方法
    • 添加、删除、遍历

      python 复制代码
      a = {1, 2, 3}
      ## 添加元素
      a.add(4)
      print(a)  ##{1, 2, 3, 4}
      python 复制代码
      ## 删除
      a.remove(4)
      print(a)  ##{1, 2, 3}
      python 复制代码
      5 in a ## in表示是否在集合中
      ## False
      python 复制代码
      ## 遍历
      for i in a:
          print(i) 
      ##
      1
      2
      3

第五章 函数与python库的使用

5.1 函数

  1. 函数的定义

    • 函数定义:

      • def(关键字) func(函数名)(arg1,arg2)(参数,可没参数,不可没括号):(冒号)

        (缩进)do something

        (缩进)return value

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

    • print():Print是一个放入对象就能将结果打印的函数

    • input():Input是一个可以让用户输入信息的函数

    • len():Len是一个可以测量对象长度的函数

    • int():Int是一个可以将字符串类型转为整数的函数

  2. 函数的定义(实战)

    python 复制代码
    ## 求最大值
    def get_max_value(a,b):
        res = a
        if b > a:
            res = b
        return res
    get_max_value(2,3)
    
    ##结果
    3
    python 复制代码
    ## 不带参数无返回值
    def print_hello():
        print("hello wrold")
    
    print_hello()
    
    ##结果
    hello wrold
    python 复制代码
    ## 计算1~100的整数和
    def get_max(n):
        res = 0
        for i in range(1, n+1):
            res += i
        return res
    
    ## 结果
    get_max(100)
    
    def get_sum(n, is_old):
        ## 计算1~n之间的整数和,is_old表示是否只计算偶数
        res = 0
        for i in range(1, n+1):
            if is_old:
                if i % 2 == 0:
                    res += i
            else:
                res += i
        return res
    
    get_sum(100, True)
    ##结果
    2550
    
    get_sum(100, False)
    ##结果
    5050
    • 参数是可变的

      python 复制代码
      def add_to_list(array, x):
          ##向array列表里面加入x
          array.append(x)
          return array
      
      a = [1,2,3]  ##增加4
      add_to_list(a,4)
      ## 结果
      [1, 2, 3, 4]
  3. 默认参数和可变参数

    • 默认参数

      python 复制代码
      ## 1~n之间的整数和,还需要判断是否只求偶数
      def get_sum(n, is_even=False): ## 函数参数带有赋值的写法就是默认参数
          res = 0
          for x in range(1, n + 1):
              if is_even:
                  if x % 2 == 0:
                      res += x
              else:
                  res += x
          return res
      
      get_sum(3, is_even=True) ## 如果有默认值
      
      ## 结果
      2
      
      get_sum(n=3)
      ## 结果
      6
      python 复制代码
      def add_two_num(a=0, b=0):
          print("a={}, b={}".format(a,b))
          return a + b
      
      add_two_num(4, 5)
      ## 结果
      a=4, b=5
      9
      
      ### 函数调用的写法
      add_two_num(a=3, b=4) ##调用时候带上名字
    • 可变参数

      python 复制代码
      ### 很多整数相加,个数不确定
      def add_nums(*args): ## 参数前面加*号表示个数不确定
          print(type(args))
          print(len(args))
          res = 0
          for x in args:
              res += x
          return res
      
      add_nums(1, 2, 3, 4, 5)
      ## 结果
      <class 'tuple'>
      5
      15
  4. 关键字参数

    python 复制代码
    def print_info(**kw): #kw = key word
        #print(kw)
        #print(type(kw))
        #print("name={}, age={}".format(name,age))
        print(kw['age'])
        for key in list(kw.keys()):
            print("key={},value={}".format(key,kw[key]))
    print_info(name="zhangsan",age=23,height=180) ##把参数跟对应的值都包装成一个字典
    
    ##
    23
    key=name,value=zhangsan
    key=age,value=23
    key=height,value=180
    
    print_info(name="zhangsan",age=23)
    
    ##
    {'name': 'zhangsan', 'age': 23}
    <class 'dict'>{'name': 'zhangsan', 'age': 23}
    <class 'dict'>
  5. 全局变量和局部变量

    python 复制代码
    value = 10 #全局变量
    
    print(value)
    print(id(value))
    ## 
    10
    2171826039376
    
    def change_value():
        #global value ##利用global关键字定义全局变量
        value = 12   ##局部变量,只限于函数体里面的
        print(value)
        print(id(value))
    
    change_value()
    
    ##
    12
    21718260393762171826039376
  6. map映射函数

    python 复制代码
    def squre(x):
        return x * x
    
    squre(3)
    ## 9
    
    
    nums = [1,2,3,4]
    nums2 = [3,4,5]
    
    def add(a,b):
        return a + b
    
    res = []
    for x in nums:
        res.append(squre(x))
        #print(suqre(x))
    print(res)
    
    ## [1, 4, 9, 16]
    
    list(map(squre,nums))  ##map第一个参数是处理的函数,第二个是处理的序列,map可以看成一个批处理接口
    
    ## [1, 4, 9, 16]
    
    result = map(add,nums,nums2,[1,2])
    
    for x in result:  ##map返回的是可迭代对象
        print(x)
    
    ##
    5
    8
    
    result = map(squre,nums)
    hasattr(result,"__iter__") ##返回True则是可迭代对象
    
    ## True
    
    def add(*nums):
        res = 0
        for x in nums:
            res += x
        return res
  7. lambda表达式

    python 复制代码
    nums2 = [3,4,5]
    
    tmp = lambda x: x * x ## lambda关键字表示定义lambda表达式
    type(tmp)
    
    ## function 函数
    
    (lambda x: x * x)(5)
    
    ## 25
    
    (lambda a,b: a+b)(3,4)
    
    ## 7
    
    nums = [1,2,3,4]
    nums2 = [3,4,5]
    
    result = map(lambda x: x*x,nums)result = map(lambda x: x*x,nums)
    
    result1 = map(lambda x,y: x + y,nums,nums2)
    
    for x in result1:
        print(x)
    
    ## 
    4
    6
    8
    
    (lambda *x: res = 0, for i in x:res +=1, res)(1,2,3)
    ## 
    SyntaxError: invalid syntax
        ## 注意,一般不用lambda语句执行多条逻辑语句

5.2 Python中的库

  1. Python中的库

    Python 复制代码
    ## 调用模块的东西
    ## 在jupyter notebook中新建txt文件,分别命名为test_module.py和test_module2.py,再新建一个package包,将两个新建的txt文件放入进去,再在package里新建一个__int__.py文件
    ## test_module.py输入以下内容
    NAMEA = 'zhangsan'
    
    
    def print_hello():
        print("hello wrold")
    ## test_module2.py输入以下内容
    def print_hello():
        print("hello world 2")
        
    
    import test_module ## import后面的模块名
    
    test_module.print_hello()
    
    ## hello wrold
    
    print(test_module.NAME)
    
    ## zhangsan
    
    test_module.NAME = "李四"
    print(test_module.NAME)
    
    ## 李四
    
    
    
    
    ##调用方法二
    from test_module import print_hello ##from模块导入函数,变量,类
    print_hello()
    from test_module import NAME
    NAME
    
    ##
    hello wrold
    '李四'
    
    import package.test_module
    
    package.test_module.print_hello()
    
    ## hello wrold
    
    from package.test_module2 import print_hello
    
    print_hello()
    
    ## hello world 2
python 复制代码
import math
dir(math)

math.pi
## 3.141592653589793
math.sqrt(4)math.sqrt(4)
## 2.0


from package import test_module2
dir(test_module2)

##
['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'print_hello']



import matplotlib.pyplot as plt ## as是设置别名,起个小名,Python不自带的就是第三方库
plt.plot([4,2,3,1])

第六章 文件操作、序列化与反序列化

6.1 文件操作

  1. 文件操作

    python 复制代码
    ## 打开
    def open(file(文件名字), mode(模式)='r', buffering=None, errors=None, newline=None, closefd=True):
    ## open打开文件需要返回对象    
    
    file.close() ##关闭文件
    模式参数 说明
    r 只读形式打开文件,默认模式
    w 打开文件并写入,没有就创建文件,文件由内容则先清空
    a 打开文件,并在文件已有内容后面追加
    python 复制代码
    ##读文件
    file.read()	##读整个文件内容
    file.readline() ##读取一行内容
    file.readlines() ##读取所有行并返回列表形式
    python 复制代码
    ##写文件
    file.write(str)	##写入字符串
    file.writelines(seq) ##传入字符串序列
  2. 实际操作

    • 读文件

      python 复制代码
      ## 新建data.txt文件,输入以下内容
      zhangsan
      hello world
      
      file = open("data.txt",mode='r') ##读取文件
      
      print(file)
      type(file)
      
      ##
      <_io.TextIOWrapper name='data.txt' mode='r' encoding='cp936'>
      _io.TextIOWrapper
      
      ## 不需要用,则必须关闭文件
      file.close()
      
      ##判断打开的文件是否关闭,True表示已经关闭,就不能操作了,False表示打开的文件没有关闭,可以操作
      file.closed
      
      ## True
    python 复制代码
    ## with打开写法
    with open("data.txt", mode='r') as file:
        ##操作文件
        ##读取数据(file.read(),file.readline(),file.readlines())
        ##读取所有的行
        #a = file.read()
        b = file.readline()
        #print(a) ##read是读取全部的文件内容
        print(b)
        #print(type(a))
        print(type(file))
    print(file.closed) ##用with写法执行,运行之后自动关闭了
    
    ##
    zhangsan
    #zhangsan
    #hello world
    #<class 'str'>
    <class '_io.TextIOWrapper'>
    True 
    python 复制代码
    with open("data.txt", mode="r") as file: ## file指定全路径或者文件名(必须要文件和程序是同一级目录)
        ## 读取数据,file.read(),file.readline(),file.readlines()
        ## readline读取所有行
        array = [] ## 存放所有的行
        line = file.readline()
        while line:
            #print(line)
            line = line.strip() ## strip可以去掉字符串的换行符
            array.append(line)
            line = file.readline()
        """
        a = file.readline()
        print(a) ## readline是每次读取一行
        print(type(a))
        b = file.readline()
        print(b)
        print(type(file))
        """
        print(array)
        
    print(file.closed) ## 自动关闭了
    
    ## 
    ['zhangsan', 'hello world']
    True
    python 复制代码
    with open("data.txt",mode='r') as file:
        a = file.readlines() ##readlines返回所有行的是个列表
        a = list(map(lambda x: x.strip(), a)) ##调用map函数进行去掉换行符(\n)
        print(a)
    print(file.closed) ## 自动关闭了
    
    ## 
    ['zhangsan', 'hello world']
    True
    • 计算求值案例

      python 复制代码
      ## 新建scores.txt文件,输入以下内容
      ## stu_id是人员1编号,score是1分数
      stu_id,score
      u0,25
      u1,4
      u2,75
      u3,65
      u4,95
      u5,59
      u6,36
      u7,24
      u8,46
      u9,3
      u10,23
      u11,94
      u12,86
      u13,96
      u14,10
      u15,3
      u16,64
      u17,24
      u18,54
      u19,61
      u20,49
      u21,28
      u22,36
      u23,84
      u24,28
      u25,80
      u26,78
      u27,90
      u28,51
      u29,84
      u30,83
      u31,30
      u32,10
      u33,60
      u34,31
      u35,37
      u36,15
      u37,72
      u38,68
      u39,3
      u40,45
      u41,31
      u42,28
      u43,36
      u44,20
      u45,61
      u46,11
      u47,31
      u48,29
      u49,0
      u50,44
      u51,85
      u52,73
      u53,63
      u54,44
      u55,42
      u56,26
      u57,21
      u58,21
      u59,28
      u60,57
      u61,18
      u62,55
      u63,51
      u64,12
      u65,70
      u66,40
      u67,90
      u68,62
      u69,24
      u70,51
      u71,27
      u72,32
      u73,92
      u74,19
      u75,53
      u76,65
      u77,48
      u78,76
      u79,26
      u80,96
      u81,40
      u82,26
      u83,25
      u84,93
      u85,96
      u86,36
      u87,86
      u88,59
      u89,23
      u90,63
      u91,98
      u92,40
      u93,77
      u94,93
      u95,39
      u96,78
      u97,63
      u98,14
      u99,38
      python 复制代码
      ## 读取所有的行
      with open("scores.txt",mode="r") as file:
          lines = file.readlines()
          #lines = list(map(lambda x: x.strip(),lines))
      #print(lines)
      scores = []
      for x in lines[1:]:
          x = x.strip() ##去除空行
          scores.append(x.split(",")[1]) ## 跳过表头,从第二行开始,获取逗号后面的数据
      #
      #print(scores)
      mean_value = 0 ##定义平均值
      max_value = 0 ##判断最大值,定义一个最小值
      min_value = 100 ##判断最小值,定义一个最大值
      #因为从文本拿出来的scores分数是字符串,所以需要转换为整数
      for x in scores:
          x = int(x) ##转为整数
          mean_value += x
          if x > max_value:
              max_value = x
          if x < min_value:
              min_value = x
      mean_value /= len(scores)
      
      
      
      print(mean_value)
      print(max_value)
      print(min_value)
      
      ## 
      48.54
      98
      0
    • 写文件

      python 复制代码
      ## 写入文件
      ## 文件写入数据,新建一个result.txt文件。file.write(str), file.writelines(seq)
      
      with open("result.txt", mode="w") as file: ##模式如果没有文件,则会自动新建该文件
          #print(file)
          file.write(str(mean_value)+'\n') ##必须转为字符串类型才可以写入,如果要换行就加"\n"
          file.write(str(max_value)+"\n")
          file.write(str(min_value)+"\n")
          
          
      with open("result1.txt", mode="w") as file: ##模式如果没有文件,则会自动新建该文件
          ## writelines是字符串的列表,如果需要换行则字符串本身需要包含"\n"
          file.writelines([str(mean_value)+"\n",str(max_value)+"\n",str(min_value)+"\n"])
          
          
          
      ##reslut.txt和result1.txt有数据
      48.54
      98
      0
      
      #注意,w是覆盖文件内容
      python 复制代码
      ## 追加模式
      with open("result.txt", mode="a") as file: # w模式如果没有文件,就新建一个
          print(file) ## write是把参入的字符串写入在一行
          file.write("\n") ## 追加模式可以先进行换行操作
          file.write(str(mean_value)+"\n") ## 如果要换行就加"\n"
          file.write(str(max_value)+"\n")
          file.write(str(min_value))
          
      ## a为追加模式,即追加文件内容

6.2 序列化和反序列化

  1. 序列化:

    • 概念:简单地说,将对象转化为"串行化"数据形式,存储在硬盘或者通过网络传输到其他地方。

    python 复制代码
    import pickle   #导入序列化的库
    
    pickle.dump(obj,file)  #序列化接口
    python 复制代码
    #序列化
    import pickle   #导入序列化的库
    
    data = {"name":"zhangsan","age":30}
    
    with open("data.pkl",mode="wb")as file:  ## wb文件模式表示写二进制模式
        #往文件里面序列化
        pickle.dump(data, file)  ###pickle.dump(obj,file) ,obj就是序列化的对象,file就是序列化的文件
    ## 注意,生成的文件用记事本打开是乱码
    python 复制代码
    ## 封装成一个函数
    ## 目的,可以直接调用,更加简便
    def save_object(obj,file):
        with open(file, mode="wb") as fp:
            pickle.dump(obj, fp)
            
    
    save_object(data, "data.pkl")
    
    
    ## 保存列表
    save_object([1,2,3,4], "data.pkl")
    
    load_object("data.pkl")
    
    ##
    [1, 2, 3, 4]
  2. 反序列化:

    • 概念:简单地说,读取"串行化"数据形式,并转化为对象。

    python 复制代码
    import pickle   #导入序列化的库
    
    pickle.load(file)  #反序列化接口
    python 复制代码
    #反序列化
    with open("data.pkl",mode="rb") as file:
        # pickle.load(file)  file就是反序列化的文件
        a = pickle.load(file)
        print(a)
    
    ##
    {'name': 'zhangsan', 'age': 30}
    python 复制代码
    ## 封装成一个函数
    ## 目的,可以直接调用,更加简便
    def load_object(file):
        with open(file, mode="rb") as fp:
            result = pickle.load(fp)
        return result
    
    load_object("data.pkl")
    
    ##
    {'name': 'zhangsan', 'age': 30}

第七章 面向对象和异常处理

7.1 面向对象

  1. 面向对象的定义和使用:

    • 定义

      • 类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
      • **类变量:**类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
      • **数据成员:**类变量或者实例变量, 用于处理类及其实例对象的相关的数据。
      • **方法重写:**如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
      • **局部变量:**定义在方法中的变量,只作用于当前实例的类。
      • **实例变量:**在类的声明中,属性是用变量来表示的。这种变量就称为实例变量,是在类声明的内部但是在类的其他成员方法之外声明的。
      • **继承:**即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待
      • **实例化:**创建一个类的实例,类的具体对象。
      • **方法:**类中定义的函数。
      • **对象:**通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。
    • 使用:

      python 复制代码
      #类
      ## 一:
      class GrilFriend:
          ## 类的方法,函数
          def say_hello(self): ##self 参数是必须的,并且占在第一个位置
              print("你好,张三!")
              
      
      xiao_hua = GrilFriend()
      type(xiao_hua)
      
      ## __main__.GrilFriend
      
      ## 调用类的方法
      xiao_hua.say_hello()
      
      ## 你好,张三!
      
      xiao_tiantian = GrilFriend()
      xiao_tiantian.say_hello()
      
      ## 你好,张三!
      
      
      
      
      ## 二:
      class GrilFriend:
          ## 类的方法,函数
          def say_hello(self, num): ##self 参数是必须的,并且占在第一个位置
              for i in range(num):
              	print("你好,张三!")
                  
                  
      xiao_hua = GrilFriend()
      xiao_hua.say_hello(3)
      
      ## 
      你好,张三!
      你好,张三!
      你好,张三!
      
      
      
      ## 三:
      class GrilFriend:  ## 女朋友肯定是女性
          gender = '女的'  ## gender表示性别,这种声明的属性,表示类的公共属性
          ## 类的方法,函数
          def say_hello(self, num): ##self 参数是必须的,并且占在第一个位置
              for i in range(num):
                  print("你好,张三!")
                  
                  
      xiao_hua = GrilFriend()
      xiao_hua.gender
      
      ## 女的
      
      
      
      ## 四:
      class GrilFriend:  ## 女朋友肯定是女性
          gender = '女的'  ## gender表示性别,这种声明的属性,表示类的公共属性
          ## 私有属性
          def __init__(self, name, look):  ## __init__是构造方法,Python中独有的方法
              self.name = name   ## self表示我们定义的实际对象
              self.look = look
          ## 类的方法,函数
          def say_hello(self, num): ##self 参数是必须的,并且占在第一个位置
              print("来自{}的问候.".format(self.name))
              for i in range(num):
                  print("你好,张三!")
                  
      
                  
      xiao_hua = GrilFriend("小花", "90")
                           
      print(xiao_hua.look)
      xiao_hua.name
                            
      ##
      90
      '小花'
      
      xiao_hua.say_hello(3)
      
      ##
      来自小花的问候.
      你好,张三!
      你好,张三!
      你好,张三!
  2. 面向对象的三大特性:

    • 封装

      python 复制代码
      ## 封装
      ## 流程式的编写代码------>到函数式的编写代码------>再到面向对象
      ## 例如:
      # 流程式:
      sum = 0
      for i in range(1, 100):
          sum += i
      print(sum)
      
      # 函数式:
      def get_sum(n):
          sum = 0
          for i in range(1, n):
              sum += i
          print(sum)
      
      get_sum(100)
      
      # 面向对象:
      class Operator:
          name = "计算器类"
          def get_sums(self, n):
              sum = 0
              for i in range(1, n):
                  sum += i
              print(sum)
          def mupltiply(self, n):
              res = 1
              for i in range(1, n):
                  res *= i
              print(res)
              
      a = Operator()
      a.get_sums(100)
      a.mupltiply(5)
      
      
      ##
      4950
      4950
      4950
      24
    • 继承

      python 复制代码
      #类
      class GrilFriend:  ## 女朋友肯定是女性
          gender = '女的'  ## gender表示性别,这种声明的属性,表示类的公共属性
          ## 私有属性
          def __init__(self, name, look):  ## __init__是构造方法,Python中独有的方法
              self.name = name   ## self表示我们定义的实际对象
              self.look = look
          ## 类的方法,函数
          def say_hello(self, num): ##self 参数是必须的,并且占在第一个位置
              print("来自{}的问候.".format(self.name))
              for i in range(num):
                  print("你好,张三!")
                  
      
      ## 陪打游戏女朋友、陪编程女朋友、陪唱歌女朋友、陪学习女朋友
      ## 继承GrilFriend
      class GameGrilFirend(GrilFriend):  ## 类的名字后面的括号里面写需要继承的类,类所包含的属性和方法就是自己的和继承的总和
          def game(self):
              print("打游戏 ing...")
      class CodeGrilFriend(GrilFriend):
          def code(self):
              print("写代码 ing...")
      class SingGrilFriend(GrilFriend):
          def sing(self):
              print("唱歌 ing...")
      class StudyGrilFriend(GrilFriend):
          def study(self):
              print("学习 ing...")
              
      
      ### 继承单个
      gf1 = GameGrilFirend("小美", 7)
      
      gf1.game()
      ## 打游戏 ing...
      
      gf1.game()
      ## 小美
      
      gf1.gender
      ## 女
      
      gf1.look
      ## 7
      
      gf1.say_hello(3)
      ##
      来自小美的问候.
      你好,张三!
      你好,张三!
      你好,张三!
      
      gf3 = SingGrilFriend("小花", 9)
      
      gf3.sing()
      ## 唱歌 ing...
      
      
      
      ### 继承多个
      class FullGrilFriend(GameGrilFirend, CodeGrilFriend, SingGrilFriend, StudyGrilFriend):
          pass  ## pass意味着没有逻辑,略过这里,不写代码
      
      
      gf4.code()
      
      gf4.sing()
      
      gf4.game()
      
      gf4.study()
      
      gf4.name
      
      ##
      写代码 ing...
      唱歌 ing...
      打游戏 ing...
      学习 ing...
      '小三'
    • 多态

      python 复制代码
      #类
      class GrilFriend:  ## 女朋友肯定是女性
          gender = '女的'  ## gender表示性别,这种声明的属性,表示类的公共属性
          def like(self):
              return "爱好"
          ## 私有属性
          def __init__(self, name, look):  ## __init__是构造方法,Python中独有的方法
              self.name = name   ## self表示我们定义的实际对象
              self.look = look
          ## 类的方法,函数
          def say_hello(self, num): ##self 参数是必须的,并且占在第一个位置
              print("来自{}的问候.".format(self.name))
              for i in range(num):
                  print("你好,张三!")
                  
                  
      
      ## 陪打游戏女朋友、陪编程女朋友、陪唱歌女朋友、陪学习女朋友            
      ## 继承GrilFriend
      class GameGrilFirend(GrilFriend):  ## 类的名字后面的括号里面写需要继承的类,类所包含的属性和方法就是自己的和继承的总和
          def like(self):
              return "打游戏"
          def game(self):
              print("打游戏 ing...")
      class CodeGrilFriend(GrilFriend):
          def like(self):
              return "写代码"
          def code(self):
              print("写代码 ing...")
      class SingGrilFriend(GrilFriend):
          def like(self):
              return "唱歌"
          def sing(self):
              print("唱歌 ing...")
      class StudyGrilFriend(GrilFriend):
          def like(self):
              return "学习"
          def study(self):
              print("学习 ing...")
              
              
      def get_like(gf):
          print("张三女朋友的爱好是:{}".format(gf.like()))  ## 约定张三女朋友都有like方法返回对应的爱好
      
      gf5 = GameGrilFirend("小小", 7)
      
      get_like(gf5)
      ## 张三女朋友的爱好是:打游戏
      
      gf6 = CodeGrilFriend("小美",6)
      
      get_like(gf6)
      ## 张三女朋友的爱好是:写代码
      
      
      class RunGrilFriend(GrilFriend):
          def like(self):
              return "跑步"
          
      gf7 = RunGrilFriend("小红", 9)
      
      get_like(gf7)
      ## 张三女朋友的爱好是:跑步

7.2 异常处理

  1. 异常处理

    python 复制代码
    try:
    		{执行代码
    except:
    		{发生异常时执行代码
    else:
    		{没有异常时执行代码
    finally:
    		{不过有没有异常时都要执行代码
    • 案例:

      python 复制代码
      ## 张三想结婚了
      ## 处理流程
      try:
      		{张三相亲
      except:
      		{性别、年龄、身高
      else:
      		{和对方在一起
      finally:
      		{二狗子总要结婚
      python 复制代码
      # a / b
      a = int(input("请输入一个整数:"))  ## 将字符串强转为整型
      b = int(input("请输入二个整数:")) 
      print("{}除以{}等于:{}".format(a, b, a/b)) ##除数不能为0
      
      ##
      请输入一个整数:4
      请输入二个整数:2
      4除以2等于:2.0
      
      ## 改进
      # a / b
      try:
          a = int(input("请输入一个整数:"))  ## 将字符串强转为整型
          b = int(input("请输入二个整数:")) 
          print("{}除以{}等于:{}".format(a, b, a/b)) 
      except ZeroDivisionError:
          print("除数不能为0")
      
      ##
      请输入一个整数:4
      请输入二个整数:0
      除数不能为0
      
      ## 继续改进
      # a / b
      while True:
          try:
              a = int(input("请输入一个整数:"))  ## 将字符串强转为整型
              b = int(input("请输入二个整数:")) 
              print("{}除以{}等于:{}".format(a, b, a/b)) 
              if a == 0:
                  break
          except ZeroDivisionError:
              print("除数不能为0")
          except ValueError:
              print("输入格式错误!")
          except: ### except:这种最好是放到其他错误里面
              print("有问题")
          else:
              print("没有错误")
          finally:
              print("计算结束")
              
      ##
      请输入一个整数:4
      请输入二个整数:2
      4除以2等于:2.0
      没有错误
      计算结束
      请输入一个整数:4
      请输入二个整数:q
      输入格式错误!
      计算结束
      请输入一个整数:4
      请输入二个整数:0
      除数不能为0
      计算结束
      
      
      
      ### 注意,如果运行卡死就重启
  2. 断言-assert关键字和抛异常-raise关键字:

    • assert示例:

      python 复制代码
      ## 示例
      
      ### [x1, x2, x3], [y1, y2, y3] -> x1*y1+x2*y2+x3*y3
      def get_list_sum(list1, list2):
          result = 0
          for i in range(len(list1)):
              result += list1[i] * list2[i]
          return result
      
      get_list_sum([1,2], [2])
      
      ## IndexError: list index out of range
      python 复制代码
      ### assert关键字
      
      def get_list_sum(list1, list2):
          assert len(list1) == len(list2), "两个列表长度必须一致"  ## assert断言是假设的意思
          result = 0
          for i in range(len(list1)):
              result += list1[i] * list2[i]
          return result
      
      get_list_sum([1,2], [2])
      
      ## AssertionError: 两个列表长度必须一致
      
      
      try:
          get_list_sum([1,2], [2])
      except AssertionError as e:
          print(e)
      
      ##
      发生错误:
      两个列表长度必须一致
    • 抛异常raise示例:

      python 复制代码
      ### ##
      def get_list_sum(list1, list2):
          if len(list1) != len(list2):
              raise Exception("两个列表长度必须一致")
          result = 0
          for i in range(len(list1)):
              result += list1[i] * list2[i]
          return result
      
      try:
          get_list_sum([1,2], [2])
      except Exception as e:
          print(e)
          
      ## 两个列表长度必须一致
      python 复制代码
      ## 自定义错误类  # 注意,任何错误必须继承Exception
      class MyError(Exception):
          def _int__(self,message):
              self.message = message
              
      def get_list_sum(list1, list2):
      #     assert len(list1) == len(list2), "两个列表长度必须一致" ##assert断言是假设的意思
          if len(list1) != len(list2):
      #         raise Exception("两个列表长度必须一致")
              raise MyError("两个列表长度必须一致!")
          result = 0
          for i in range(len(list1)):
              result += list1[i] * list2[i]
          return result
      
      try:
          get_list_sum([1,2], [2])
      except Exception as e:
          print(e)
      
      ## 两个列表长度必须一致!
      
      get_list_sum([1,2], [2])
      
      ## MyError: 两个列表长度必须一致!
      
      
      
      
      # 改进
      class MyError(Exception):
          def __init__(self, message, len1, len2):
              self.message = message
              self.len1 = len1
              self.len2 = len2
              
      def get_list_sum(list1, list2):
          if len(list1) != len(list2):
              raise MyError("两个列表长度必须一致!",len(list1), len(list2))
          result = 0
          for i in range(len(list1)):
              result += list1[i] * list2[i]
          return result
      
      
      try:
          get_list_sum([1,2], [2])
      except MyError as e:
          print(type(e))
          print(e.len1)
          print(e.len2)
          
      ## 
      <class '__main__.MyError'>
      2
      1
相关推荐
憨憨小白1 小时前
函数的高级应用
开发语言·python·青少年编程·少儿编程
CV-King1 小时前
计算机视觉硬件知识点整理(三):镜头
图像处理·人工智能·python·opencv·计算机视觉
惟长堤一痕1 小时前
医学数据分析实训 项目三 关联规则分析作业--在线购物车分析--痹症方剂用药规律分析
python·数据分析
经纬恒润1 小时前
应用案例分享 | 智驾路试数据分析及 SiL/HiL 回灌案例介绍
数据挖掘·数据分析·智能驾驶·ai智能体
eeee~~1 小时前
GeoPandas在地理空间数据分析中的应用
python·jupyter·信息可视化·数据分析·geopandas库
Amo Xiang1 小时前
Python 常用模块(四):shutil模块
开发语言·python
Filotimo_2 小时前
【自然语言处理】实验三:新冠病毒的FAQ问答系统
人工智能·经验分享·笔记·python·学习·自然语言处理·pycharm
计算机学姐2 小时前
基于python+django+vue的影视推荐系统
开发语言·vue.js·后端·python·mysql·django·intellij-idea
扎克begod2 小时前
JAVA并发编程系列(9)CyclicBarrier循环屏障原理分析
java·开发语言·python
Book_熬夜!2 小时前
Python基础(九)——正则表达式
python·正则表达式·php