Python的简单学习:
Python在机器学习、数据分析、自然语言处理、计算机视觉中应用十分广泛。近期含着两个目的对Python进行了基本的了解:
- 拓展计算机语言的学习
和其它计算机语言当然有不同,但在学习过程中也发现了很多相通之处。 - 对人工智能领域的兴趣
该如何找到自己喜欢和擅长的事情,自己未来做什么。方法是多尝试、多体验。
下面将学习过程中整理的笔记放在这里,方便复习,如果对你有用,很荣幸哈哈。
内容主要为语法方面,包含条件判断、循环、函数、类、模块、异常处理、正则表达式等。
几天的学习比较浅薄,如有问题欢迎指正,我会好好修改,也很感谢你的指点😎。
-
打印
print("we are going to do sth") print('we are going to do sth') print("we're going to do sth") print('we\'re going todo sth') #其中斜杠转义 拼接字符串: print('apple'+'4') print('apple'+str(4)) #加上引号就是打印字符串,输出结果为:apple4 print('1+4') #输出结果为:1+4 print(1+4) #输出结果为:5 print(int('1')+4) #输出结果为:5 print(float('1.2')+2) #输出结果为:3.2
-
数学运算
+ - * / % ** // //求次方用'**’ 3**2 #输出结果为:9 //取整用'//' 9//4 #输出结果为:2
-
自变量
a = 1 b = a*2 print(a, b) #输出结果为:1 2
-
循环
(1)while循环
while condition < 10 print(1) condition = condition + 1
(2)for循环
example_list = [0,2,4,6,8] for i in example_list: print(i) #输出结果为:0 2 4 6 8,所以表中数据被赋值给了i for i in range(1,10): print(i) for i in range(1,10,2): print(i)
-
条件判断
(1)if
x = 0 if x > 1: print('x > 1') elif x < 1: print('x < 1') #条件满足后就会忽略剩下的语句,跳出循环 else: print('x = 1')
-
函数
(1)无参
def function(): a = 1 b = 2 c = a+b print(c) function()
(2)有参
def fun(a, b): c = a * b print("a*b的结果是:",c) fun(2,3)
(3)默认参数
*非默认参数要被放在默认参数之前。
def sale_car(price, color='red', brand='carmy', is_second_hand=True): print('price:', price, 'color:', color, 'brand:', brand, 'is_second_hand:',is_second_hand) sale_car(1000) //输出结果为:price: 1000 color: red brand: carmy is_second_hand: True //也可以对默认参数进行修改 sale_car(1000, color='blue') //输出结果为:price: 1000 color: blue brand: carmy is_second_hand: True
(4)全局&局部变量
APPLE = 100 #APPLE就是一个全局变量 def fun(): a = 10 #a就是一个局部变量 global b #b就是一个全局变量,使用'global'定义 b = 20 print(a) return a+100 print(fun()) print(b) #输出结果为: 10 110 20 #可以将b打印出来
(5)补充
-
函数定义时,不需要定义数据类型,调用函数时将数据类型书写正确即可;
def sale_car(price, color, brand, is_second_hand): print('price:', price, 'color:', color, 'brand:', brand, 'is_second_hand:',is_second_hand) sale_car(1000, 'red', 'carmy', True) //输出结果为:price: 1000 color: red brand: carmy is_second_hand: True
-
-
模块
(1)导入模块
import time print("hello world!!!") time.sleep(5) print("hello world!!!") #直接导入模块,然后调用其中函数 ------------------------------------------------------- from time import sleep #结合下一点可以看出只要from...(模块)import...(功能)就可以直接调用 print("hello") sleep(5) print("hello") #确定使用模块的函数,直接调用 ------------------------------------------------------- from time import * #使用模块中的所有函数,*表示所有 print("hello") sleep(5) #此处可以直接调用函数 print("hello") ------------------------------------------------------- import time as tt #使用as设置别名 print("hello world!!!") tt.sleep(5) #使用别名调用函数 print("hello world!!!")
使用第三方的包:
法一:在命令提示符内
pip install 包名称 #直接国外网站下载,速度较慢 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名称 #使用清华大学提供的镜像网站下载,速度较快
法二:在PyCharm内部安装
点击界面右下角Python解释器版本,点击"Interpreter Settings",搜索需要的包进行下载。 可以勾选"Options",输入"-i https://pypi.tuna.tsinghua.edu.cn/simple"更快下载。
(2)自建模块
任何的脚本都可以当作模块
#创建一个python文件,如"m1",在其中定义方法: def printdata(data): print(data) #创建另一个python文件,如"test",在其中导包: import m1 m1.printdata("I am m1") #输出结果为:I am m1 #"m1.py"和"test.py"需要在同一个目录内或者"m1.py"在外部资源库中
-
读写文件
(1)写文件
text = ('this is my first.\nthis is next line.\nthis is last line.') print(text) my_file = open('my file.txt', 'w') #创建一个文件,'w'代表读写模式 my_file.write(text) #将text写入文件 my_file.close() #记得关闭文件 append_text = ('\nthis a new sentence.') my_file = open('my file.txt', 'a') #'a'即"append" my_file.write(append_text) #写入新的句子 my_file.close()
(2)读文件
my_file = open('my file.txt', 'r') #'w'代表读写模式 content = my_file.read() print(content) #将文件中内容输出 content_line = my_file.readlines() #readlines()表示全部读取并存储在数组中 print(content_line) #该输出结果为:['this is my first.\n', 'this is next line.\n', 'this is last line.\n', 'this a new sentence.']
-
class 类
class Caculator: name = 'Good calculator' #定义类的属性 price = 18 def __init__(self, name, price, length, width, weight): #初始化属性 self.name = name self.price = price self.length = length self.width = width self.weight = weight def add(self, x, y): #定义方法 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) result = x*y print(result) def divide(self, x, y): result = x / y print(result) calcul = Caculator('Bad calculator', 15,12, 5, 20) #使用该类 calcul_name = calcul.name #获取属性 calcul_prince = calcul.price print(calcul_price) print(calcul_name) print(calul.add(3, 1)) #调用类中的方法
-
input键盘录入
a_input = input("Enter a number: ") #注意input()的返回值是字符串类型,使用时注意数据类型 print("this number is:", a_input)
-
元组、列表
(1)一维
a_list = [10,21,32,43,54,65] for content in a_list: #直接遍历 print(content) for index in range(len(a_list)): #利用索引遍历 print("index=", index,"number in a_list is:", a_list[index]) #突发补充:如果要求打印列表中奇数位的元素怎么办? #使用索引遍历的方式: for index in range(0,len(a_list),2): print("index=", index,"number in a_list is:", a_list[index])
a = [1, 2, 3, 4, 5] #关于索引 print(a[-1]) #输出结果为:5,即最后一位,其余以此类推 print(a[0:3]) #输出结果为:[1, 2, 3] print(a[3:5]) #输出结果为:[4, 5] print(a[:3]) #输出结果为:[1, 2, 3] 起始位置开始 print(a[3:]) #输出结果为:[4, 5] 末尾位置结束 print(a[-2:]) #输出结果为:[4, 5] #关于方法 a.index(2) #获取'2'第一次出现时的索引 a.count(4) #获取'4'出现的次数 a.sort() #将列表a从小到大重新排列 a.sort(reverse=True) #将列表a从小到大重新排列 a = [1, 1, 2, 3, 4, 5, -1] a.remove(3) print(a) #输出结果为:[1, 1, 2, 4, 5, -1] a.remove(1) print(a) #输出结果为:[1, 2, 4, 5, -1],注意只会remove第一个'1'
(2)多维
multi_dim_a = [[1,2,3], [4,5,6], [7,8,9]] print(multi_dim_a[0][1]) #输出结果为:2
-
字典
字典的每个键值对 key:value 用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
d = {1:"apple", 2:"pear", 3:"banana"} print(d[1]) #输出结果为apple #增加键值对 d[4] = "strawberry" print(d) #输出结果为:{1: 'apple', 2: 'pear', 3: 'banana', 4: 'strawberry'} #删除键值对 del d[3] print(d) #输出结果为:{1: 'apple', 2: 'pear', 4: 'strawberry'} #值可以取任意数据类型,如字典 d1 = {1:"apple", 2:"pear", 3:"banana", 4:{1:"a", 2:"b"}} print(d1[4][2]) #输出结果为:b
-
break & continue
while True: b = input("Enter a number: ") if b == '1': break #b == '1'则结束循环 print(b)
while True: b = input("Enter a number: ") if b == '1': #b == '1'则进行下一次循环 continue elif b == '2': break print(b)
-
异常处理try
try: file = open('my_file.txt', 'r+') except Exception as e: #捕获异常 print(e) #输出异常 response = input('do you want to creat a new file?\nyes or no: ') if response == 'yes': file = open('my_file。txt', 'w') else: pass else: #无异常则正常运行 file.write('this is a new sentence!') file.close()
-
zip/lambda/map
(1)zip
a = [1, 2, 3] b = [4, 5, 6] list(zip(a, b)) #将a与b竖向拼接 print(list(zip(a, b))) #输出结果为:[(1, 4), (2, 5), (3, 6)] for i, j in zip(a, b): print(i, j) #可用于两个列表交错输出
(2)lambda
#正常定义一个运算函数: def func1(x, y): return x + y print(func1(1, 2)) #使用lambda定义一个运算函数: func2 = lambda x, y: x + y print(func2(1, 2))
(3)map
map() 会根据提供的函数对指定序列做映射。
如果函数有多个参数, 但每个参数的序列元素数量不一样, 会根据最少元素的序列进行。
#我们仍使用上述函数 func2 = lambda x, y: x + y print(func2(1, 2)) new_list = list(map(func2, [1, 2], [3, 4])) print(new_list) #运行结果为:[4, 6],即1与2,3与4,对应作为函数的参数
-
copy & deepcopy
(1)copy
import copy a = [1, 2, [3, 4]] b = a print(id(a) == id(b)) #输出结果为:Ture,a与b一个地址,那么改变a的同时会改变b c = copy.copy(a) print(c) print(id(a) == id(c)) #输出结果为:False,a与c不是一个地址 print(id(a[2]) == id(c[2])) #输出结果为:Ture,a[2]与b[2]一个地址,一个改变另一个也会改变 #使用copy,浅部分会完全copy过来,但第二层[3, 4]仍是一个地址
(2)deepcopy
import copy a = [1, 2, [3, 4]] b = copy.deepcopy(a) #实现了完全的copy print(id(a) == id(b)) #输出结果为:False,a与c不是一个地址 print(id(a[2]) == id(b[2])) #输出结果为:False,a[2]与b[2]不是一个地址
-
pickle
import pickle a_dict = {1:"apple", 2:"pear", 3:"banana"} file = open('pickle_example.pickle', 'wb') #创建'pickle_example.pickle'文件 pickle.dump(a_dict, file) #写入a_dict file.close() with open('pickle_example.pickle', 'rb') as file: #使用with,不需要调用close() a_dict1 = pickle.load(file) #将文件中内容赋给a_dict1 print(a_dict1)
-
set
集合(set)是一个无序的不重复元素序列。
char_list = ['a', 'b', 'c','a', 'b', 'c'] print(set(char_list)) #输出结果为:{'b', 'c', 'a'},达到去重效果但乱序(同字典) print(type(set(char_list))) #输出结果为:<class 'set'>,数据类型为'set' #set()的参数只能是单个列表 sentence = 'welcome to my notes!' print(set(sentence)) #同样可以去重 #输出结果为:{'s', '!', 'l', 'c', 'o', 'y', 'n', 'm', ' ', 'e', 't', 'w'} #注意“空格”也作为一个字符保留了下来
-
正则表达式RegEx
用来匹配字符的一种工具,常被用在网页爬虫,文稿整理,数据筛选等方面,最常用的就是用在网页爬虫,数据抓取。
import re pattern1 = "cat" pattern2 = "bird" string = "The dog ran towards the cat" print(pattern1 in string) print(pattern2 in string) #平常匹配 ##使用正则表达式(1) print(re.search(pattern1, string)) #输出结果为:<re.Match object; span=(24, 27), match='cat'> print(re.search(pattern2, string)) #输出结果为:None ##使用正则表达式(2):可使用中括号增加选择 pattern3 = "r[ua]n" #"run" or "ran" print(re.search(pattern3, string)) #输出结果为:<re.Match object; span=(8, 11), match='ran'> ##使用正则表达式(3):可在中括号中使用'-'表示范围 pattern4 = "r[a-z]n" print(re.search(pattern3, string)) #输出结果为:<re.Match object; span=(8, 11), match='ran'>
正则表达式中也有各种符号来涵盖一定内容,如’\d’表示任意数字(符号较多,故使用时再进行搜索即可)。
*此处关于正则表达式只做简单了解,需要时再对‘re’包中函数进行了解使用。
-
细碎
(1)Python中以空格位置分隔/区分结构体;