深度学习入门之python基础 发布于 2024-06-10 1033 次阅读 预计阅读时间: 14 分钟 计划的深度学习入门学习路线是 编程基础python(参考课程为莫烦老师学python) — 深度学习理论入门(李宏毅深度学习入门)– 深度学习代码实战(李沫动手学深度学习)。这一篇文章学习第一部分python基础的学习笔记。 print的用法 >> > print(we are going to do sth) //打印字符型内容要加引号,单引号双引号都行File "<stdin>", line 1print(we are going to do sth)^SyntaxError: invalid syntax>> > print('we are going to do sth')//加了单引号输出成功we are going to do sth>> > print("!I'm cq") //如果字符中有单引号,那用双引号就不会冲突!I'm cq>> > print('apple' + 'eat') //字符之间可以用“+”进行拼接appleeat>> > print('apple' + '4') //此处是把4也看成一个字符apple4>> > print('apple' + str(4)) //当然,把4用str函数转换成字符也是可以的apple4>> > print(int('1')+2) //可以在print函数内直接进行数学运算3>> >Copy 数值运算 # >> > 2 + 2 # 4 # >> > 2 - 2 # 0 # >> > 2 * 2 //乘法是* # 4 # >> > 2 / 2 # 1.0 # >> > 2 ** 2 //乘方是**,和C不一样,C是^ # 4 # >> > 8 % 2 //取余运算 # 0 # >> > 9 % 4 # 1 # >> > 9/2 //一个/号是浮点数除法 # 4.5 # >> > 9//2 //两个/号是整除(取整) # 4 # >> >Copy 自变量 apple_fruit= 1print(apple_fruit) app_age = 2**4print(app_age) a = 1b = 2c = 3d=b**cprint(a, b, c, d)Copy while循环 # condition = 1# while condition < 10:# print(condition)# condition += 1 while True: print(1)Copy for循环 //example_list = [1, 3, 5, 7, 3, 7, 8, 2, 5, 7, 3563, 36446, 635] #列表 可改变for i in example_list: print(i) print("outer of for") ''' # 内部函数# range(1,3) [1,2] //range是左闭右开for i in range(1, 10, 2): print(i) # 1# 3# 5# 7# 9Copy if条件分支 x = 1y = 2z = 3 if x > y: //注意后面有引号 print("x is greater than y")else: print("x is less than y") m = 1 n = 1 if m == n: print("m is equal to n") if x < y: print("x is less than y")elif x == y: //注意Python用的是elif,C用的是else if,不一样,同样后面有引号 print("x is equal to y")else: print("x is greater than y")Copy def函数 # def函数 a = 1b = 2c = a + bprint(c) def function(a, b):c = a + bprint('this c is ', c) function(1,2) //调用function函数Copy 函数参数默认值 def sale_car(price, color='red', brand='carmy', is_second_hand='True'): //如果要给参数设置默认值,要在后面加上=某值,且赋予默认值的参数必须在最后面,否则会报错 print('price:', price, 'colour', color, 'brand', brand, 'is_second', brand, ) # sale_car(1000,'red','carmy', 'True')sale_car(1001212, 'brue')Copy 全局变量&局部变量 APPLE = 100 //全局变量需要在最外面声明,局部变量是定义在某个函数里面的a=None def fun(): global a //如果实在要在函数内部定义全局变量,需加上global前缀,并在外面提前声明,如第二行 a = 10 print(a) # 10 return a+100print(a) # Noneprint(fun()) #110print(a)Copy 写文件 text = "This is my first line.\nThis is my next line."# print(text) my_file = open('my file.txt', 'w') //以只写方式打开文件,my_file可以理解为文件指针my_file.write(text) //向该文件写入text的内容my_file.close() //一定要及时关闭Copy 文件添加内容 # text = "This is my first line.\nThis is my next line."# print(text)append_text="\nThis is a appended file" my_file = open('my file.txt', 'a')my_file.write(append_text)my_file.close()Copy 读文件 file = open('my file.txt','r') //以读的方式打开文件 content = file.readline() //readline函数一次读取一行,再次调用读取第二行allcontent = file.readlines() //readlines函数读取全部# ['This is my first line.\n', 'This is my next line.\n', 'This is a appended file\n', 'This is a appended file'] print(allcontent)Copy class类 # class后的类名开头大写,这是规范不是强求 class Calculator: #定义一个类,完成计算器的功能 name = "Good calculator" #计算器的名字叫Good calculator price= 10000 #计算器的价格是10000 def add(self, x, y): #定义在类里的函数第一个参数要写self,以调用自身 print(self.name) #在执行加法运算前先打印计算器名字 result = x + y print(result) def minus(self, x, y): result = x - y print(result) def times(self, x, y): result = x * y print(result) def divide(self, x, y): result = x / y print(result) # 调用 cal = Calculator() #定义一个个体为这个class类print(cal.name) # Good calculatorprint(cal.price) # 10000cal.add(10, 11) # Good calculator 21cal.minus(10,11) #-1Copy init功能 # class后开头大写#init是构造类时很常用的一个初始化函数class Calculator: def __init__(self, name, price, hight=18, width=29, weight=5): #init赋默认值的方法和函数一样 self.n = name self.p = price self.h = hight self.wi = width self.we = weight def add(self, x, y): # 默认self result = x + y print(result) def minus(self, x, y): result = x - y print(result) def times(self, x, y): result = x * y print(result) def divide(self, x, y): result = x / y print(result) # 调用 cal = Calculator('Good', 10000) #在有init函数后。创建个体的时候就需要对初始值进行赋值,当然有默认值的不需要 print(cal.n) #Goodprint(cal.p) #10000print(cal.h) #18print(cal.wi) #29print(cal.we) #5print(cal.add(1,2)) #3Copy input a_input = input("Please give a number:") #可以理解为附赠提示词的输入if a_input == '1': print("Yes")elif a_input == '2': print("No")else : print("Good Luck")Copy 元组和列表 # tuple list元祖和列表 a_tuple = (1, 2, 3) #元祖可以用小括号或者无括号another_tuple = 1,2,3a_list = [4, 5, 6] #列表是用中括号的 # for content in a_list:# print(content) for index in range(len(a_list)): print("index=",index,"number in list=", a_list[index]) # index = 0 # number in list = 4 # index = 1 # number in list = 5 # index = 2 # number in list = 6Copy list列表其他用途 # list列表其他用处a = [1, 2, 33, 4, 1, 56, 7, -1]# a.append(123) # appendprint(a) a.insert(1, 0) # 往下标为1的地方插入值为0的元素print(a) a.remove(33) # 删除值为33的元素,如果有多个则删除第一个print(a) print(a[0]) # 打印下标为0的元素的值print(a[-1]) # 打印下标最后一位的值 print(a[0:3]) #冒号的意思是从什么到什么,左闭右开,比如这个是从0到2print(a[:3]) #如果冒号左边不写默认从0开始print(a[3:]) #如果冒号右边不写默认到结尾 print(a[-3:]) #从倒数第三位到结尾 # 索引print(a.index(1)) # 值为1的元素在列表第几位print(a.count(1)) # 值为1的元素出现几次 # 排序a.sort(reverse=True) #将a列表从大到小排序,并覆盖原列表,如果括号里为空则为从小到大排序 print(a)Copy 多维列表 # 多维列表a = [1, 2, 3, 4, 5] multi_dim_a = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]print(a[1])print(multi_dim_a[0][2]) #3 # 切片转成np.array()处理import numpy as np # 对于ndarray的切片,格式为[x1:x2, y1:y2],截取行数为[x1,x2),列数为[y1,y2)。左边闭空间,右边开空间。# 如果要截取某一行,格式为[x,:],截取某一列:[:,y],很好理解,取某一行就是列全选,所以列用冒号# 其他截取以此类推 list = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]list_ndarray = np.array(list)list_t = list_ndarray[1:3, 1:3]print(list_t) # 输出如下# [[ 6 7]# [10 11]Copy 字典 # 字典 {键值对} 无序 里面放什么都行 a_list = {1, 2, 3, 4, 5} #这是列表d = {'apple': [1,2,3], 'pear': 2, 'orange': {1:'111',2:'222'}} #字典的key可以是很多形式,字符串、数字都行 print(d) print(d['apple']) #打印出key为apple所对应的内容,结果为1 2 3del d['apple'] #删除值为apple的key以及对应的内容 d['b'] = 20 #若字典里没有这个key,则新增该key print(d)print(d['orange'][1]) # {1:'111',2:'222'}套娃Copy import载入模块 # 载入模块有四种形式 import time import time as t #相当于重命名,最常用 from time import time,localtime #只需要time库里的time和localtime两个功能,但不需要写t. from time import * #需要time库里的全部功能 print(localtime())Copy 导入自己的模块 自定义模块要和主程序放在同一目录下,例如m1.py文件的内容为 def printdata(data): print(data)Copy 主程序的内容为 import m1 # 凡在site-packages里面也可以 m1.printdata(123)Copy 把m1.py文件放入lib文件夹里也可以直接载入,相当于从网上下载模块。 break和continue a = Truewhile a: b = input('type something:') if b == '1': break else: pass print('still in while') print('finish run')Copy 当输入为1时直接跳出循环,并且不会执行still in while语句。 a = Truewhile a: b = input('type something:') if b == '1': continue else: pass print('still in while') print('finish run')Copy 输入1时仍会执行still in while语句 错误处理 try: #尝试执行下面这条命令 file = open('eeeee', 'r+')except Exception as e: #如果执行失败输出下面这条语句 print("[Errno 2] No such file or directory: 'eeeee'") response = input('do you want to create a new file?') #询问是否想创建该文件 if response == 'y': file = open('eeeee', 'w') else: passelse: #这个else对应的是except file.write('ssss')Copy zip lambda map的用法 ''' zip lambda map 的用法''' a = [1, 2, 3]b = [4, 5, 6]print(zip(a, b)) #把a和b纵向压缩# <zip object at 0x000000000120E408># [(1, 4), (2, 5), (3, 6)]print(list(zip(a, b))) for i, j in zip(a, b): print(i / 2, j * 2) print(list(zip(a, a, b)))# [(1, 1, 4), (2, 2, 5), (3, 3, 6)] # lambda的用法,可以理解为匿名函数 def fun1(x, y): return (x + y) fun2 = lambda x, y: x + y #和上面的函数一样的效果 print(fun2(2, 3)) #map的用法,把函数功能和需要的参数一起打包 map(fun1, [1], [2]) #要用到的功能是fun1,参数是1和2,中括号是列表的意思print(map(fun1, [1], [2]))#<map object at 0x000001F7A22B9E80>print(list(map(fun1, [1], [2])))# [3]print(list(map(fun1, [1,3], [2,1]))) #当然,参数可以是更长的列表#[3, 4]Copy 浅复制和深复制 import copy #copy需要导入库 a = [1, 2, 3]b = a #这一步其实是让b指向a同样的内存地址 id(a) # id是硬盘索引id(b) # 两个是一样的,证明赋值语句其实就是把两个变量指向同一块内存 b[0] = 11 #因此如果改变b,a里的值也会跟着变print(a)# [11, 2, 3] c = copy.copy(a) # 浅复制print(id(c) == id(a)) #这里就是false了c[1]=111print(a) #此时不会不会改变a的值 n = [1, 2, [3, 4]] #但如果是列表里有列表m=copy.copy(n) #此时还用浅复制的话print(id(m) == id(n)) #这里会是Falseprint(a[2]==b[2]) # 但这里就是ture了# 这是因为浅复制相当于把n列表里的两个数和一个列表地址复制过来了,所以列表地址指向相同的地方 e = copy.deepcopy(n) #这时要用到深复制,连列表地址都不一样的复制 print(e[2]==n[2]) #此时为FalseCopy pickle打包 import pickle a_dict = {'da': 111, '2': [1, 3, 5]}file = open('pickle_example.pickle', 'wb') # wb二进制写入pickle.dump(a_dict, file) #dump大卡车把a_dict的内容倒进file里file.close #过了一天,想用打包里的数据了 file = open('pickle_example.pickle', 'rb') #rb二进制读a_dict1 = pickle.load(file)file.close()print(a_dict1) # 或者用with简写,省去close(),效果和上面一样 with open('pickle_example.pickle', 'rb') as file: a_dict1 = pickle.load(file)print(a_dict1)Copy set集合 #set是一个集合,类似列表和元组,它是一个容器char_list = ['a', 'b', 'b', 'c', 'c', 'c']print(set(char_list)) #set集合,将列表中所有重复元素删除只留下一个print(type(set(char_list))) #类型为set sentence = 'Welcome Back to This Tutorial'print(set(sentence)) #同样可以剔除字符串 unique_char = set(char_list)unique_char.add('x') # 可以添加字符,但一次只能添加一个print(unique_char) unique_char.clear() #将set里的内容全部清楚 unique_char.remove('x') # 将x移除 # set交集set1 = unique_charset2 = {'a', 'b'} print(set1.difference(set2)) # set1有set2没有的东西,cprint(set1.intersection(set2)) # 交集Copy 正则表达式 #主要是爬虫 import re # 正则表达式pattern1 = 'cat'pattern2 = 'bird'string = 'dog runs to cat' print(re.search(pattern1, string)) print(re.search(pattern2, string)) # 匹配多种可能 ,使用[]# r[au]n ran,run都可被识别 # 更多种 # [0 - 9]# [a - z]# [0-9a-z] # 特征数字匹配Copy 更多匹配规则点这里
Comments NOTHING