美文网首页
《莫烦Python3基础教程》学习笔记2

《莫烦Python3基础教程》学习笔记2

作者: python小白22 | 来源:发表于2020-06-28 16:21 被阅读0次

    一.外部模块安装

    外部模块就是在 import一些东西去python 脚本的时候会用到的.
    比如Numpy属于外部模块,在windows中,可以在Numpy 安装包的网站找到 numpy 的各种版本的安装包.

    二.文件读取

    1. \n表示换行命令
    text='This is my first test.\nThis is next line.\nThis is last line.'
    print(text)  #\n为换行命令,要注意斜杠方向
    """
    This is my first test.
    This is next line.
    This is last line.
    """
    

    2.用open打开一个文件,open的第一个参数为文件名及路径;第二个参数为形式,其中:"w"表示write,"r"表示read.

    my_file=open('my file.txt','w') #打开文件
    my_file.write(text)  #文件中写入之前定义的text
    my_file.close()  #关闭文件
    

    3.给文件添加一行

    append_text='\nThis is appended file.' 
    print(append_text)
    my_file=open('my file.txt','a')  #'a'表示append追加
    my_file.write(append_text)
    my_file.close()
    

    4.读取文件内容

    file=open('my file.txt','r')
    content=file.read() #读取文件全部内容
    print(content)
    """
    This is my first test.
    This is next line.
    This is last line.
    This is appended file.
    """
    
    file=open('my file.txt','r')
    content=file.readline() #读取第一行
    second_read_time=file.readline() #读取第二行
    print(content,second_read_time)
    """
    This is my first test.
     This is next line.
    """
    
    file=open('my file.txt','r')
    content=file.readlines() #读取所有行,python_list形式
    print(content)
    """
    ['This is my first test.\n', 'This is next line.\n', 'This is last line.\n', 'This is appended file.']
    """
    

    三.class类

    1.用class定义一个类.

    class Calculator: #类的名称首字母要大写,注意冒号
        name='Good calculator' #class的属性
        def add(self,x,y):    #定义class的功能  
            print(self.name)
            result=x+y
            print(result)
        def minus(self,x,y):
            result=x-y
            print(result)
        def times(self,x,y):
            print(x*y)
        def divide(self,x,y):
            print(x/y)
    cal=Calculator() #这里运行class时一定要加()
    

    2.class类init功能
    init(前后为双下划线)可以理解成初始化class的变量,可以在运行时,给初试值赋值.

    class Calculator: 
        def __init__(self,name,price,hight=12,width=15,weight=20): #给属性设置默认值
            self.name=name
            self.price=price
            self.h=hight
            self.wi=width
            self.we=weight
    c=Calculator('Bad calculator',10)
    print(c.name,c.price,c.h,c.wi,c.we)
    """
    Bad calculator 10 12 15 20
    """
    

    四.input输入

    1.variable=input(): 表示运行后,可以在屏幕中输入一个数字,该数字会赋值给自变量.

    a_input=input('Please give a number:')
    print('This input number is:',a_input)
    """
    Please give a number:12   #input12
    This input number is: 12
    """
    

    2.input()应用在if中,若input不定义成整型,则if语句中的自变量a_input对应的1和2应写成字符串形式.

    a_input=int(input('Please give a number:')) #定义成int()整数型
    if a_input==1:
        print('This is a good one')
    elif a_input==2:
        print('See you next time')
    else:
        print('Good luck')
    """
    Please give a number:1    #input1
    This is a good one
    """
    

    五.元组tuple 列表list

    1.元组tuple用小括号或者无括号来表示,列表list用中括号来表示,它们都表示一连串有顺序的数字,它们的元素可以一个一个被迭代、输出、运用、定位取值.

    a_tuple=(12,3,5,15,6) #元组
    another_tuple=2,4,6,7,8
    a_list=[12,3,67,7,82] #列表
    for content in a_list: #一个一个按顺序输出
        print(content)
    """
    12
    3
    67
    7
    82
    """
    for index in range(len(a_tuple)):  #len表示length,元组的长度
        print('index=',index,'number in list=',a_tuple[index])
    """
    index= 0 number in list= 12
    index= 1 number in list= 3
    index= 2 number in list= 5
    index= 3 number in list= 15
    index= 4 number in list= 6
    """
    

    2.list添加

    a=[1,2,3,4,2,3,1,1]
    a.append(0) #给a的最后面添加一个0
    a.insert(1,0) #在a的位置1处添加0
    print(a)
    #[1, 0, 2, 3, 4, 2, 3, 1, 1, 0]
    

    注:列表位置从0开始
    3.list移除

    a=[1,0,2,3,4,2,3,1,1,0]
    a.remove(2) #移除掉a中第一次出现的2
    print(a)
    #[1, 0, 3, 4, 2, 3, 1, 1, 0]
    

    4.list索引

    a=[1,0,3,4,2,3,1,1,0]
    print(a[0]) #打印a中第0位的值
    #1
    print(a[-1]) #打印a中最后一位的值
    #0
    print(a[0:3]) #打印a中第0,1,2位即前三位的值
    #[1,0,3]
    print(a[5:]) #打印a中第五位及其之后的值
    #[3,1,1,0]
    print(a[-3:]) #打印a中倒数第三位及其之后的值
    #[1,1,0]
    print(a.index(2))  #列表中第一次出现2的索引
    #4
    print(a.count(1)) #列表中出现1的次数
    #3
    

    5.list排序

    a=[1,0,3,4,2,3,1,1,0]
    a.sort() #默认对a从小到大排序
    print(a)
    #[0, 0, 1, 1, 1, 2, 3, 3, 4]
    a.sort(reverse=True) #对a从大到小排序
    print(a)
    #[4, 3, 3, 2, 1, 1, 1, 0, 0]
    

    6.多维列表

    multi_dim_a=[[1,2,3],
                 [2,3,4],
                 [3,4,5]] #多维列表,三行三列
    print(multi_dim_a[0][0]) #打印第0行第0个位置
    #1
    print(multi_dim_a[2][2]) #打印第2行第2个位置
    #5
    

    六.字典dictionary

    字典没有顺序;以大括号的形式表示;有key和value两种元素,数字和字符串都可以当做key和value,字典的元素可以是一个列表、可以是一个function、还可以是字典,形式多样.

    d= {'apple':[1,2,3],'pear':{1:3,3:'c'},'orange':3} #一个key对应一个value
    d2={1:'a','c':'b'} #key和value可以是字符串或数字
    print(d['apple']) #打印d中的apple
    #[1,2,3]
    print(d['pear'][3]) #打印d中的pear中的3
    #c
    del d['pear'] #删除d中的pear
    print(d)
    #{'apple': [1, 2, 3], 'orange': 3}
    d['b']=20 #给d中加入b
    print(d)
    #{'apple': [1, 2, 3], 'orange': 3, 'b': 20}
    

    七.import 载入模块

    方法一:

    import time #加载time模块,python自带
    print(time.localtime()) #print出当地时间
    """
    time.struct_time(tm_year=2020, tm_mon=6, tm_mday=24, tm_hour=17, tm_min=18, tm_sec=31, tm_wday=2, tm_yday=176, tm_isdst=0)
    """
    

    方法二:

    import time as t #把time简称为t
    print(t.localtime)
    """
    time.struct_time(tm_year=2020, tm_mon=6, tm_mday=24, tm_hour=17, tm_min=18, tm_sec=31, tm_wday=2, tm_yday=176, tm_isdst=0)
    """
    

    方法三:

    from time import time,localtime #只要time和localtime两个功能
    print(localtime())
    print(time())
    """
    time.struct_time(tm_year=2020, tm_mon=6, tm_mday=24, tm_hour=17, tm_min=18, tm_sec=31, tm_wday=2, tm_yday=176, tm_isdst=0)
    1592990311.6439924
    """
    

    方法四:

    from time import* #import所有功能
    print(time())
    """
    1592990311.6439924
    """
    

    八.continue和break

    1.跳出循环:当a=False时,会执行接下来的语句后再跳出这个循环.

    a=True
    while a:
        b=input('type something')
        if b=='1':
            a=False
        else:
            pass
        print('still in while')
    print('finish run')
    """
    type something2
    still in while
    type something1
    still in while    #会执行下面的语句再跳出
    finish run
    """
    

    2.break:当符合跳出条件时,会直接结束循环.

    while True:
        b=input('type something')
        if b=='1':
            break
        else:
            pass
        print('still in while')
    print('finish run')
    """
    type something2
    still in while
    type something1
    finish run    #直接跳出循环
    """
    

    3.continue:当满足条件时,不会执行 else 后面的代码,而会直接进入下一次循环.

    while True:
        b=input('type something')
        if b=='1':
            continue
        else:
            pass
        print('still in while')
    print('finish run')
    """
    type something2
    still in while
    type something1    #不执行else后的代码,直接进入下一次循环   
    type something
    """
    

    九.错误处理try

    1.输出错误

    try:
        file=open('eeee','r')  #会报错的代码
    except Exception as e:  #接收错误,储存在e中
        print(e)
    """
    [Errno 2] No such file or directory: 'eeee'
    """
    

    2.处理错误

    try:
        file = open('eeee', 'r+w')
    except Exception as e:
        print('there is no file named as eeee') #首先报错
        response = input('do you want to create a new file')  #决定是否输入y
        if response == 'y':    
           file = open('eeee', 'w')  #输入y后,会新建一个文件
        else:
            pass
    else:
        file.write('ssss')  #再次运行,文件中会写入ssss
    file.close()
    """
    there is no file named as eeee
    do you want to create a new filey
    """
    

    十.zip lambda map

    1.zip函数接受任意多个(包括0个和1个)序列作为参数,合并后返回一个tuple列表

    a=[1,2,3]
    b=[4,5,6]
    ab=zip(a,b)  #把a和b竖向合并
    print(list(ab))  #加list可视化这个功能
    """
    [(1, 4), (2, 5), (3, 6)]
    """
    for i,j in zip(a,b):
        print(i/2,j*2)  #zip中的运算
    """
    0.5 8
    1.0 10
    1.5 12
    """
    print(list(zip(a,a,b))) #可以zip更多元素
    """
    [(1, 1, 4), (2, 2, 5), (3, 3, 6)]
    """
    

    2.lambda定义一个简单函数,有简化代码的功能.

    fun2=lambda x,y:x+y  #x,y为自变量,x+y为具体运算
    print(fun2(2,3))
    #5
    

    3.map把函数和参数绑定在一起.

    def fun1(x,y):
        return(x+y)
    print(list(map(fun1,[1],[2])))
    """
    [3]
    """
    print(list(map(fun1,[1,3],[2,5])))
    """
    [3,8]
    """
    

    十一.浅复制&深复制 copy&deepcopy

    1.赋值

    import copy #加载copy模块
    a=[1,2,3]
    b=a   #赋值
    print(id(a)) #a在内存中的地址
    #1932900954560
    print(id(a)==id(b))  #赋值后,两者id相同
    #True
    b[0]=11  #改变b的第一个值,a也会改变
    print(a)
    #[11, 2, 3]
    

    2.浅拷贝

    a=[1,2,3]
    c=copy.copy(a)  #浅拷贝,只拷贝了a的外围对象本身
    print(id(a)==id(c))
    #False
    c[1]=222222 #改变c的第二个值,a不会被改变
    print(a,c)
    #[1, 2, 3] [1, 222222, 3]
    
    a=[1,2,[3,4]]  #第三个值为列表,是内部元素
    d=copy.copy(a) #只用浅拷贝只是对内部元素的引用
    print(id(a)==id(d))
    #False
    print(id(a[2])==id(d[2]))
    #True
    a[0]=11 #改变a中的第一个值,d不会改变
    print(d)
    #[1, 2, [3, 4]]
    a[2][0]=333 #改变a的内部元素的一个值,d也会改变
    print(d)
    #[1, 2, [333, 4]]
    

    5.深拷贝

    a=[1,2,[3,4]]
    e=copy.deepcopy(a) #深拷贝,对外围和内部对象都进行了拷贝
    a[2][0]=33  #改变a中内部元素列表第一个的值,e不会改变
    print(e)
    #[1, 2, [3, 4]]
    print(id(e[2])==id(a[2]))
    #False
    

    十二.pickle 保存数据

    pickle 是一个压缩/保存/提取文件的模块,pickle可以保存字典、列表和变量等.
    1.pickle保存

    import pickle
    a_dict={'da':111,2:[23,1,4],'23':{1:2,'d':'sad'}}
    file=open('pickle_example.pickle','wb')
    pickle.dump(a_dict,file)
    file.close()
    

    2.pickle提取

    with open('pickle_example.pickle','rb') as file: #会自动关闭文件
        a_dict1=pickle.load(file)
    print(a_dict1)
    

    十三.set找不同

    1.set基本

    char_list=['a','b','c','c','d','d','d']
    print(set(char_list)) #找list中的不同元素
    #{'d', 'c', 'b', 'a'}
    sentence='Welcome Back to This Tutorial'
    print(set(sentence))
    #{'e', 'k', 'T', 's', 'o', 'W', 'h', 'B', ' ', 'r', 'm', 'i', 'u', 't', 'a', 'c', 'l'}
    

    2.添加元素add

    unique_char=set(char_list)
    unique_char.add('x')  #添加元素,只能单独加一个
    print(unique_char)
    #{'b','a','x','c','d’}
    

    3.清除元素:清除一个元素可以用 remove 或者 discard,remove清除不存在元素时会报错,discard清除不存在元素时会继续返回原有数据;而清除全部可以用 clear.

    unique_char.remove('x')  #清除元素x
    print(unique_char)
    #{'b', 'a', 'c', 'd'}
    unique_char.discard('d')  #清除元素d
    print(unique_char)
    #{'b', 'a', 'c'}
    unique_char.clear()  #清除全部元素
    

    4.筛选操作

    set1=unique_char
    set2={'a','e','i'}
    print(set1.difference(set2))  #set1与set2不同的部分
    #{'x', 'b', 'c', 'd'}
    print(set1.intersection(set2)) #set1与set2相同的部分
    #{'a'}
    

    相关文章

      网友评论

          本文标题:《莫烦Python3基础教程》学习笔记2

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