- 内置函数
map``filter``reduce``zip
的作用? - 装饰器,特殊的函数?
- 调用函数,@timer语句会找到函数定义上面的装饰器timer,并把函数作为参数传递给装饰器,即
- 运行timer(i_can_sleep())
- 为带参数的函数添加装饰器,下列输出中,每次运营都会在前面加start 后面加stop
- for i in range(10):
- my_print(i, i + 1)
- 绘制简单曲线
- plt.plot([1,2,5], [4, 8, 10])
- plt.show()
- # x轴的定义域为-3.14到正3.14,中间取100个点
- x = np.linspace(-np.pi, np.pi,100)
- plt.plot(x, np.sin(x))
- # 显示所画的图形
- plt.show()
- x = np.linspace(-np.pi 2, np.pi 2, 100)
- plt.figure(1, dpi = 50) # 创建图表1,dpi代表分辨率、精细程度,越大越精细
- # 画四条线
- for i in range(1,5):
- plt.plot(x, np.sin(x/i))
- # 显示所画的图形
- plt.show()
- plt.figure(1, dpi = 50)
- data = [1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 6, 4]
- # 绘制直方图,只要传入数据,直方图就会统计数据出现的次数
- plt.hist(data)
- x = np.arange(1,10)
- y = x
- fig = plt.figure()
- # 绘制散点图,c=‘r’表示散点为红色,marker = ‘o’,表示散点为圆形
- plt.scatter(x,y,c = ‘r’, marker = ‘o’)
- plt.show()
- 使用pandas读取csv数据
- # 输出头部以查看数据是否正确读取
- print(iris.head())
- 使用seaborn设置样式
- # 设置绘制格式为散点图
- sns.jointplot(x=’120’, y=’4’, data=iris, size=5)
- # distplot绘制曲线
- sns.distplot(iris[‘120’])
- # 绘制散点图
- iris.plot(kind=’scatter’, x=’120’, y=’4’)
- plt.show()
- FaceGrid一般绘图函数
- hue彩色显示分类0/1/2,virginica是数据中最后一列的列名称
- plt.scatter 绘制散点图,传入的两个参数分别是散点图横轴合纵轴的名称
- add_legend()显示分类的描述信息
内置函数map``filter``reduce``zip
的作用?
filter(function or None, iterable)
a = [1,2,3,4,5]
via = lambda x:x>2
print(list(filter(via, a)))
a = [1,2,3]
b = [2,3,4]
add = lambda x,y:x+y
print(list(map(add, a, b)))
reduce
- 不能直接使用,需要从
functools
模块中引入 - 作用是将一个序列中的每一个元素和一个单个初始值做指定的函数运算
- 比如给定初始值1,列表[2,3,4],函数
x+y
,结果是1+2=3,3+3=6…from functools import reduce
re = reduce(lambda x,y:x+y, [2,3,4], 1)
print(re)
zip
```python for a in zip((1,2,3),(4,5,6)):
print(a)
dica = {‘a’:’aa’, ‘b’:’bb’}
dicb = zip(dica.values(), dica.keys())
print(dict(dicb))
<a name="Tuklm"></a>
#### 闭包
- 外部函数定义的变量被内部函数引用,就叫闭包?
```python
# 用闭包实现counter
def counter(FIRST):
cnt = [FIRST]
def add():
cnt[0] += 1
return cnt[0]
return add
num5 = counter(5)
num6 = counter(6)
# num5是一个函数,因此下面的语句打印出来是函数
print(num5)
# 因为num5是函数,因此为其加上括号,得到函数的返回值?
print(num5())
~
为什么内部函数的返回值不要带小括号?
def a_line(a,b):
return lambda x:a*x+b
line1 = a_line(1,2)
print(line1(3))
装饰器,特殊的函数?
- 和闭包有点像
```python import time
def timer(func): def wrapper(): start_time = time.time() func() stop_time = time.time() print(stop_time - start_time) return wrapper
@timer def i_can_sleep(): time.sleep(3)
调用函数,@timer语句会找到函数定义上面的装饰器timer,并把函数作为参数传递给装饰器,即
运行timer(i_can_sleep())
i_can_sleep()
函数`func()`,不写括号的话`func`,代表什么?
<a name="LUZid"></a>
#### 如何为带参数的函数添加装饰器?
```python
def tips(func):
def inner(x,y):
print('start')
func(x,y)
z = 1
print('stop')
return
return inner
@tips
def add(a,b):
print(a+b)
@tips
def sub(a,b):
print(a-b)
# 为带参数的函数添加装饰器,下列输出中,每次运营都会在前面加start 后面加stop
print(add(1,2))
print(sub(2,1))
装饰不同的函数,展示不同的效果
- 无限套娃🪆
```python
def new_tips(arg_name):
def tips(func):
return tipsdef inner(x,y):
print('start %s %s' %(arg_name, func.__name__))
func(x,y)
z = 1
print('stop')
return
return inner
@new_tips(‘加法’) def add(a,b): print(a+b)
@new_tips(‘减法’) def sub(a,b): print(a-b)
为带参数的函数添加装饰器,下列输出中,每次运营都会在前面加start 后面加stop
print(add(1,2)) print(sub(2,1))
<a name="Oz0kP"></a>
#### 上下文管理器with
<a name="D88G9"></a>
#### 类
<a name="bUN0U"></a>
#### 在面向对象的编程语言中,“变量”被称作“属性”,“函数”被称作“方法”
<a name="e2f0R"></a>
#### 类的封装:
- 定义给类的属性,通过在属性前加两条下划线的形式,实现:不能通过赋值改变,只能通过类定义的方法改变
```python
class Player():
def __init__(self, name, hp, occu):
self.__name = name # 把name属性封装
self.hp = hp
self.occu = occu
def print_player(self):
print("玩家 %s 的血量是:%s, 职业: %s" %(self.__name, self.hp,
self.occu))
def rename(self, new_name):
self.__name = new_name
user1 = Player('1', '100', 'war')
user2 = Player('2', '99', 'hunter')
user1.name = '3' # 被封装的name属性不能通过简单的赋值方式来访问
user1.print_player()
user2.print_player()
tips:当需要写多个类时,通常先将每个类都定义出来,但不填充其中的内容,而是将其pass
掉,从而厘清逻辑关系
- 类可以继承
- 子类直接拥有父类的属性,不需要初始化
- 如果要重新按照父类的形式,初始化某个属性,给予其不同于父类的默认值,可以使用
super()
- 子类中定义的方法,会覆盖掉父类中的同名方法;即同一个方法,在不同类的实例上,用出来的效果是出不同的,同一个方法有多种的状态,这就叫方法的多态;
- “多态”和“继承”都是面向对象的编程的特点;
- 可以通过
isinstence(实例, 类)
来判断某个实例是否是某个类的子类实例; - 实际上在python3中,数字、列表、字符串等都是类;
- 所有的对象都继承自
object
类,甚至type()
也是;
38. 类的使用-自定义with语句
with open()
非常的方便:
- 跳出with自动关闭,避免忘记写关闭语句的情况
能不能自己实现这种操作呢?
这里open是一个类,在这个类中实现了自动关闭的方法
所以只要自己定义一个类,在定义中实现对应的方法即可
这两个方法分别是__enter__()
和__exit__()
class Testwith():
def __enter__(self):
print('run')
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
with Testwith():
print('test in running')
# 输出结果:
Press ENTER or type command to continue
run
test in running
exit
可以看到,作用就是在开始和结束都做一些“动作”
也可以在退出的时候,自定义处理错误发生的情况:
class Testwith():
def __enter__(self):
print('run')
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_tb is None:
print('nromal exit')
else:
print('has error %s' %exc_tb)
with Testwith():
print('test in running')
raise NameError('test name error')
# 输出结果:
Press ENTER or type command to continue
run
test in running
has error <traceback object at 0x7fa0caaf2d70> # 自定义的错误处理方式
Traceback (most recent call last):
File "with_test.py", line 12, in <module>
raise NameError('test name error')
NameError: test name error
shell returned 1
39. 并发、多线程编程的定义
- 一个进程, 多个线程 ```python import threading import time from threading import current_thread
def my_print(arg1, arg2): print(current_thread().getName(), ‘start’) print(“%s %s” %(arg1, arg2)) time.sleep(1) print(current_thread().getName(), ‘stop’)
for i in range(10):
my_print(i, i + 1)
for i in range(10): t1 = threading.Thread(target = my_print, args = (i, i+1)) t1.start()
print(current_thread().getName(), ‘end’)
```python
import threading
from threading import current_thread
class Mythread(threading.Thread):
def run(self):
print(current_thread().getName(), 'start')
print('runing')
print(current_thread().getName(), 'stop')
t1 = Mythread()
t1.start()
t1.join()
40. 经典的生产者和消费者的问题
- 生产者生产内容,消费者消费内容
两者同时进行
用
queue
序列来储存内容- 编写两个
Thread
子类,作为生产者和消费者 - 同时实例化,同时运行 ```python from threading import Thread, current_thread import time import random from queue import Queue
queue = Queue(5)
class ProducerThread(Thread): def run(self): name = current_thread().getName() nums = range(1, 100) global queue while True: num = random.choice(nums) queue.put(num) print(‘生产者 %s 生产了数字 %s’ %(name, num)) t = random.randint(1, 3) time.sleep(t) print(‘生产者 %s 休息了 %s 秒’ %(name, t))
class ConsumersThread(Thread): def run(self): name = current_thread().getName() global queue while True: num = queue.get() queue.task_done() print(‘消费者 %s 消费了数字 %s ‘ %(name, num)) t = random.randint(1, 3) time.sleep(t) print(‘消费者 %s 休息了 %s 秒’ %(name, num))
p1 = ProducerThread(name = ‘p1’) p1.start() c1 = ConsumersThread(name = ‘c1’) c1.start() c2 = ConsumersThread(name = ‘c2’) c2.start()
<a name="QK4wG"></a>
#### 41. python标准库
- 自带的库就是标准库
- 具体哪些内容,可以去python官方网站看
<a name="U7XgB"></a>
#### 42. 正则表达式库re
<a name="E9lnE"></a>
#### 43. 正则表达式的元字符
- ^$表示空行
- .*?表示不使用贪婪模式
- 在字符串前面加上`r`,可以避免python对字符串中的`\n`等特殊字符进行转义
- `match`与`search`
- `.`任意单个字符
- `*`至少出现1次
- `?`0或1次
- `{m}`出现m次;`{m,n}`出现m到n次
- `[1234]`1234中的任意一个
<a name="oLsqd"></a>
#### 46. 正则表达式的替换函数sub、findall
- `sub`接受3个参数
- 按顺序分别是“正则表达式规则”、“新内容”、“执行替换的原文本”
```python
import re
phone = '123-456-789 # this is a phone number'
p1 = re.sub(r'#.*$', '', phone)
print(p1)
p2 = re.sub('\D', '', p1)
print(p2)
47. 日期与时间函数库
time``datetime
# import re
# phone = '123-456-789 # this is a phone number'
# p1 = re.sub(r'#.*$', '', phone)
# print(p1)
# p2 = re.sub('\D', '', p1)
# print(p2)
import time
import datetime
print(time.time())
print(time.strftime('%Y-%m-%d'))
print(time.localtime())
print(datetime.datetime.now())
new_time = datetime.timedelta(minutes=10)
print(datetime.datetime.now() + new_time)
48. 数学相关库
49. 使用命令行对文件和文件夹操作
pwd
查看当前所在位置ls
查看当前目录下文件ls -l
获取更多关于当前目录下文件的信息cd
切换到其他目录cd ..
访问上级目录mkdir
建立文件夹;若建立多级文件夹,需要传入参数-p
rmdir g
删除文件夹grm -rf /tmp/a
删除/tmp中的a和下级的所有文件
50. 文件夹操作库os.path、pathlib
51. 机器学习的一般流程和numpy库
机器学习的一般流程
- 数据采集
- 数据预处理
- 数据清洗
- 建模
- 测试
55. pandas安装与series结构
58. 层次化索引
层次化索引即多个索引,
import pandas as pd
from pandas import Series, DataFrame
# obj = Series([1, 5, 7])
#
# obj2 = Series([1,2,3], index=[1,2,3])
# print(obj2)
#
# obj2[1] = 100
# print(obj2)
# print(1 in obj2)
#
# sdata = {'beijing':1000, 'shanghai':13132, 'guangzhou':113123}
# obj3 = Series(sdata)
# print(obj3)
data = {'city':['shanghai', 'beijing', 'guangzhou'],
'year':[2016, 2017, 2018],
'pop':[1.5, 1.7, 1.9]
}
frame = DataFrame(data)
print(frame)
# 排序
frame2 = DataFrame(data, columns = ['year', 'city', 'pop'])
print(frame2)
# 提取某列的数据
print(frame['city'])
print(frame.year)
# 加列并赋值
frame2['new'] = 100
# 加列并根据表原有数据计算填值
frame2['cap'] = frame2['city'] == 'beijing'
print(frame2)
pop = {'beijing':{2008:1.5, 2009:2.0},
'shanghai':{2008:1.2, 2009:3.6}
}
# 根据嵌套字典创建dataframe
frame3 = DataFrame(pop)
print(frame3)
# 行列转置
print(frame3.T)
# 重新修改索引,注意重新修改的索引必须是原来就有的,如果没有,会全部填充为nan
obj4 = Series([1,2,4,5], index = ['a', 'b', 'c', 'd'])
obj5 = obj4.reindex(['b','d','c','a','t'], fill_value = 0)
print(obj5)
# 对于缺失值,用相邻的值进行填充
obj6 = Series(['blue', 'purple', 'yellow'], index = [0,2,4])
print(obj6.reindex(range(6), method = 'ffill'))
# 删除缺失的值
from numpy import nan as NA
data = Series([1, NA, 2])
print(data.dropna())
# 删除dataframe的缺失值
data2 = DataFrame([[1., 6.5, 3], [1., NA, NA], [NA, NA, NA]])
# 出现了缺失就丢掉
print(data2.dropna())
# 只有全部缺失才丢掉
print(data2.dropna(how='all'))
# 一整列都缺失才丢掉
data2[4] = NA
print(data2)
# 填充丢失的值为0
print(data2.fillna(0, inplace=True))
print(data2.dropna(axis=1, how='all'))
import numpy as np
data3 = Series(np.random.randn(10),
index = [['a','a','a', 'b', 'b','b','c','c','d','d'],
[1,2,3,1,2,3,1,2,2,4]])
# print(data3)
# print(data3['b'])
# print(data3['b':'c'])
# 将Series类型的数据转化为DataFrame类型的数据
print(data3.unstack())
print(data3.unstack().stack())
59. matplotlib的安装与绘图
- 安装
pip3 install matplotlib
seaborn
库,用来封装matplot,?有疑问pip install seaborn
```python import matplotlib.pyplot as plt
绘制简单曲线
plt.plot([1,2,5], [4, 8, 10])
plt.show()
import numpy as np
# x轴的定义域为-3.14到正3.14,中间取100个点
x = np.linspace(-np.pi, np.pi,100)
plt.plot(x, np.sin(x))
# 显示所画的图形
plt.show()
x = np.linspace(-np.pi 2, np.pi 2, 100)
plt.figure(1, dpi = 50) # 创建图表1,dpi代表分辨率、精细程度,越大越精细
# 画四条线
for i in range(1,5):
plt.plot(x, np.sin(x/i))
# 显示所画的图形
plt.show()
plt.figure(1, dpi = 50)
data = [1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 6, 4]
# 绘制直方图,只要传入数据,直方图就会统计数据出现的次数
plt.hist(data)
x = np.arange(1,10)
y = x
fig = plt.figure()
# 绘制散点图,c=‘r’表示散点为红色,marker = ‘o’,表示散点为圆形
plt.scatter(x,y,c = ‘r’, marker = ‘o’)
plt.show()
import pandas as pd import seaborn as sns import warnings warnings.filterwarnings(‘ignore’)
使用pandas读取csv数据
iris = pd.read_csv(‘./geekbangpython/timegeekbang.com/iris_training.csv’)
# 输出头部以查看数据是否正确读取
print(iris.head())
使用seaborn设置样式
sns.set(style=’white’, color_codes=True)
# 设置绘制格式为散点图
sns.jointplot(x=’120’, y=’4’, data=iris, size=5)
# distplot绘制曲线
sns.distplot(iris[‘120’])
# 绘制散点图
iris.plot(kind=’scatter’, x=’120’, y=’4’)
plt.show()
FaceGrid一般绘图函数
hue彩色显示分类0/1/2,virginica是数据中最后一列的列名称
plt.scatter 绘制散点图,传入的两个参数分别是散点图横轴合纵轴的名称
add_legend()显示分类的描述信息
sns.FacetGrid(iris, hue=’virginica’, size=5).map(plt.scatter, ‘120’, ‘4’).add_legend()
sns.FacetGrid(iris, hue=’virginica’, size=5).map(plt.scatter, ‘setosa’, ‘versicolor’).add_legend() plt.show()