看莫烦老师讲解的 python 基础 整理笔记, 基本和java类似, 完整的理一遍,记录一下,方便以后查看,视频地址,
https://www.bilibili.com/video/av16926522
目录
27.浅复制 & 深复制 , copy & deepcopy
1.print 3.5+ 版本需要加上括号 print()
print('apple' + 4) --> error
print('apple' + str(4))
2.运算
1+1 => 2
1-1 => 0
2*2 => 4
2**2 =>4 #平方
2**3 =>8 #平方
8%%2 =>0 #求余
8%%3 =>2 #求余
9//4 =>2 #取整
3.自变量 variable
apple = 10
apple_egg = 10 + 2
apple_fruit = apple + 3
a, b, c = 1
print(a , b, c , apple, apple_egg)
4.while 循环
condition = 1
while (condition < 10):
print(condition)
condition = condition + 1
5.for 循环
example_list = [1,2,3,4,5,13,132,4,1,2314,123]
for i in example_list:
print(i)
#改变tab 结构
#for windows: control + [
#for mac: commond + [
print('outter of for')
for i in range(1,10): #range(1,10) 前包后不包;range(1,10,2) 最后一个参数为间隔步数
print(i)
6.if 判断
x = 1
y = 2
z = 3
if x > y:
print(' X is more than Y')
if x < y < z:
print(' x is less than y, and y is less than z')
if x < y > z:
print(' x is less than y , and y is more than z')
if x <= y:
print(' x is less or equal to y')
if x == y:
print(' x is equal to y ')
if x != y:
print(' x is not equal to y')
7. if else 条件
x = 1
y = 2
z = 3
if x > y:
print(' x is greater than y')
else:
print(' x is less or equal to y')
8.if elif else
x = 4
y = 5
z = 6
if x > 1:
print('x is greater than 1')
elif x < 1:
print('x is less than 1')
else:
print('x is equal to 1')
9.def 函数
#命名+括号
def function():
print('This is a function')
a = 1 + 2
print(a)
function()
10.函数参数
def fun(a, b):
c = a*b
print('this c is', c)
fun(1, 2)
fun(a=2, b=5)
11.函数默认参数
#有默认值的参数必须放在没有默认值参数之后
def sale_car(price, color='red', brand='carmy', is_second_hand=True):
print('price:',price,
'color:',color,
'brand:',brand,
'is_sencond_hand:',is_second_hand)
sale_car(1000)
sale_car(1000,color='blue')
12.全局 & 局部变量, global & local
#全局变量一般大写
APPLE = 100
a = None
def fun():
#a = 10
#a = APPLE
global a
a = 20
return a + 100
print(fun()) #可以把全局变量直接赋给a
print(APPLE) #全局变量
print(a) #函数里加上global 后可以修改全局变量,可以打印出20
13. 模块安装
numpy;pandas;scikit-learn.....
sudo pip3 install numpy #安装
sudo pip3 uninstall numpy #卸载
sudo pip3 install - U numpy #更新
14.读写文件
#写入文件
text = 'This is my first test. \n This is next line. \n This is last line.'
my_file = open('my file.txt','w')
my_file.write(text)
my_file.close()
#追加文件内容
append_text = '\n This is appended file.'
my_file = open('my file.txt', 'a')
my_file = write(append_text)
my_file.close()
#读取txt文件
file = open('my file.txt','r') # r=>read w=>write a=>append
content = file.read()
#content = file.readline() #按行读,再次执行则读取下一行 .csv , .excel 文件
#content = file.readlines() #读取所有行,放到list 里面, .excel .csv 文件
print(content)
15. class 类
class Calculator:
name = 'Good calculator'
price = 18
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)
calcul = Calculator()
calcul.name
calcul.add(11, 11)
16. 类 init 功能
class Calculator:
name = 'Good calculator'
price = 18
def __init__(self, name, price, hight, width, weight):
self.name = name
self.price = price
self.h = hight
self.wi = width
self.we = weight
c = Calculator('Good cal',12,30,15,19)
c.name
17. input 输入
a_input = input('Please give a number')
print('This input number is :', a_input)
if a_input == str(1):
print('This is a good one')
elif a_input == '2':
print('See you next time')
else:
print('Good Luck')
18.元组 列表
#tuple元组 & list列表
a_tuple = (1,2,3,4,5)
another_tuple = 2,34,6,5,1,
a_list = [1,23,4,5,6,7]
for content in a_tuple
print(content)
for index in range(len(a_list)):
print('index=',index,'number in list=',a_list[index])
19.列表
a = [1,2,3,4,5,6,7,8]
a.append(0)
a.insert(1,0) #在指定位置插入数据0,坐标位置从0开始
a.remove(2) #参数为value,不是坐标,会把第一次出现的value移除
print(a)
print(a[0])
print(a[-1]) #最后一位,负数表示倒数的顺序
print(a[0:3]) #前三位,从0开始
print(a[:3]) #前三位,从0开始
print(a[3:5]) #位置3-5
print(a[5:]) #打印位置5以后的
print(a[-3:]) #打印倒数3位
print(a.index(2)) #打印第一次出现value 2的索引
print(a.count(2)) #打印value 2出现的次数
a.sort() #排序,从小到大
a.sort(reverse=True) #反方向排序,从大到小
print(a)
20.多维列表
更多会用到numpy , pandas
a = [1,2,3,4,5]
multi_dim_a = [[1,2,3],
[2,3,4],
[3,4,5]]
print(a[1])
print(multi_dim_a[0][1])
21.字典 dictionary
#dictionary key=value 没有顺序
a_list = [1,2,3,4,5,6]
d = {'apple':1, 'pear':2, 'orange':[2,3]} #可以嵌套包含
d2 = {1:'a','c':'b'}
print(d['apple'])
del d['pear'] #del 删除
d['b'] = 20 #添加元素key=value
22. import 载入模块
import time
print(time.localtime())
import time as t
print(t.localtime())
#只import 模块内的部分功能
from time import time,localtime
print(localtime()) #不需要在写time 或者 t
print(time())
from time import *
print(localtime())
print(getttime())
23.自己的模块
m1.py
def printdata(data):
print('I am m 1')
python1.py; 要和m1 在同一个目录;(也可以放到site-packages, 模块既可以被import)
import m1
m1.printdata('I am python1')
24.continue & break
#continue 跳出本次循环
#break 跳出循环
while True:
b = input('type something')
if b == '1'
break
#continue
else:
pass
print('finish run')
25. 错误处理 try
try:
file = open('eeee', 'r+')
except Exception as e:
print(e)
print('this is no file named as eeee')
response = input('do you want to create a new file')
if response == 'y':
file = open('eeee', 'w')
else:
pass
else:
file.write('ssss')
file.close()
26. zip lambda map
a = [1,2,3]
b = [4,5,6]
zip(a, b)
list(zip(a, b))
for i, j in zip(a, b):
print(i/2, j*2)
list(zip(a, a, b))
def fun1(x, y):
return (x+y)
fun1(1, 2)
#lambda 简化函数定义
fun2 = lambda x, y: x+y
fun2(2, 3)
list(map(fun1, [1], [2]))
#结果 [3]
list(map(fun1, [1,3], [2,5]))
#结果 [3, 8]
27.浅复制 & 深复制 , copy & deepcopy
= 赋值, 地址空间一样
copy.copy 父对象地址空间不一样,子对象的地址空间一样
copy.deepcopy 父子对象的地址空间都不一样
import copy
a = [1,2,3]
b = a
id(a) #a 的索引
print(id(a) == id(b)) #true 同一地址
c = copy.copy(a)
print(id(a) == id(c)) #false
a = [1,2,[3,4]]
d = copy.copy(a)
print(id(a) == id(d)) #false
print(id(a[2]) == id(d[2])) #true copy只会复制父对象,子对象是共用的,改变子对象,都会进行改变
e = copy.deepcopy(a)
print(id(e[2]) == id(a[2]) #false deepcopy 完全拷贝, 地址完全不会在同一空间
28.pickle 保存数据
import pickle
a_dict = {'da':111,2:[23,1,4],'23':{1:2,'d':'sad'}}
#保存pickle 文件
file = open('pickle_example.pickle', 'wb') #保存为机器可识别的格式
pickle.dump(a_dict, file)
file.close()
#读出pickle 文件
#with open('pickle_ample.pickle','rb') as file: #自动关闭,不用手动关闭
file = open('pickle_example.pickle', 'rb')
a_dict1 = pickle.load(file)
file.close()
print(a_dict1)
29. set 找不同
char_list = ['a','b','c','d','d','d']
#筛选不重复的
print(type(set(char_list)))
sentence = 'Welcome Back to This Tutorial'
print(type(set(sentence)))
unique_char = set(char_list)
unique_char.add('x')
#unique_char.clear() #清除
unique_char.remove('x') #移除元素,如果元素不存在,会报错
unique_char.discard('y') #移除元素,如果元素不存在,不报错
print(unique_char)
set1 = unique_char
set2 = {'a', 'e', 'i'}
print(set1.difference(set2)) #set1中存在,set2中不存在的元素
print(set1.intersection(set2)) #set1, set2 相同的元素
30. RegEx 正则表达
爬虫/匹配网页文本
import re
#matching string 简单Python 匹配
pattern1 = "cat"
pattern2 = "bird"
string = "dog runs to cat"
print(pattern1 in string) # true
print(pattern2 in string) # false
#用正则寻找配对
#regular expression
pattern1 = "cat"
pattern2 = "bird"
string = "dog run to cat"
print(re.search(patter1, string)) #<_sre.SRE_Match object; span=(12,15), match='cat'>
print(re.search(patter2, string)) #None
#匹配多种可能 使用[]
#multiple patterns ("run" or "ran")
ptn = r"r[au]n" #前面加上 r 后表示正则表达式
print(re.search(pth, "dog runs to cat"))
# continue
print(re.search(r"r[A-Z]n", "dog runs to cat"))
print(re.search(r"r[a-z]n", "dog runs to cat"))
print(re.search(r"r[0-9]n", "dog r2s to cat"))
print(re.search(r"r[0-9a-z]n", "dog runs to cat"))
#特殊种类匹配
#数字
# \d : decimal digit 匹配数字
# \D : any non-decimal digit 匹配非数字
......
.....
.....
.....
#Group 组
match = re.search(r"(\d+), Date: (.+)", "ID: 021523, Date:Feb/12/2017")
print(match.group()) #021523, Date: Feb/12/2017
print(match.group(1)) #021523
print(match.group(2)) #Feb/12/2017
match = re.search(r"(?P<id>\d+_, Date: (?P<date>.+)", "ID: 021523, Date:Feb/12/2017")
print(match.group('id')) #021523
print(match.group('date')) #Feb/12/2017
#寻找所有匹配
#findall
print(re.findall(r"r[ua]n", "run ran ren")) #['run', 'ran']
# | : or
print(re.findall(r"(run|ran)", "run ran ren")) #['run', 'ran']
#替换
#re.sub() replace
print(re.sub(r"r[au]ns", "catches", "dog runs to cat")) #dog catches to cat
#分裂
#re.split()
print(re.split(r"[,;\.]", "a;b,c.d;e")) #['a','b','c','d','e']
#compile 先编译表达式,在进行匹配
compiled_re = re.compile(r"r[ua]n")
print(compiled_re.search("dog ran to cat")