内置函数map``filter``reduce``zip的作用?

filter(function or None, iterable)

  1. a = [1,2,3,4,5]
  2. via = lambda x:x>2
  3. print(list(filter(via, a)))
  1. a = [1,2,3]
  2. b = [2,3,4]
  3. add = lambda x,y:x+y
  4. print(list(map(add, a, b)))

reduce

  • 不能直接使用,需要从functools模块中引入
  • 作用是将一个序列中的每一个元素和一个单个初始值做指定的函数运算
  • 比如给定初始值1,列表[2,3,4],函数x+y,结果是1+2=3,3+3=6…
    1. from functools import reduce
    2. re = reduce(lambda x,y:x+y, [2,3,4], 1)
    3. 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))

  1. <a name="Tuklm"></a>
  2. #### 闭包
  3. - 外部函数定义的变量被内部函数引用,就叫闭包?
  4. ```python
  5. # 用闭包实现counter
  6. def counter(FIRST):
  7. cnt = [FIRST]
  8. def add():
  9. cnt[0] += 1
  10. return cnt[0]
  11. return add
  12. num5 = counter(5)
  13. num6 = counter(6)
  14. # num5是一个函数,因此下面的语句打印出来是函数
  15. print(num5)
  16. # 因为num5是函数,因此为其加上括号,得到函数的返回值?
  17. print(num5())
  18. ~

为什么内部函数的返回值不要带小括号?

  1. def a_line(a,b):
  2. return lambda x:a*x+b
  3. line1 = a_line(1,2)
  4. 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()

  1. 函数`func()`,不写括号的话`func`,代表什么?
  2. <a name="LUZid"></a>
  3. #### 如何为带参数的函数添加装饰器?
  4. ```python
  5. def tips(func):
  6. def inner(x,y):
  7. print('start')
  8. func(x,y)
  9. z = 1
  10. print('stop')
  11. return
  12. return inner
  13. @tips
  14. def add(a,b):
  15. print(a+b)
  16. @tips
  17. def sub(a,b):
  18. print(a-b)
  19. # 为带参数的函数添加装饰器,下列输出中,每次运营都会在前面加start 后面加stop
  20. print(add(1,2))
  21. print(sub(2,1))

装饰不同的函数,展示不同的效果

  • 无限套娃🪆 ```python def new_tips(arg_name): def tips(func):
    1. def inner(x,y):
    2. print('start %s %s' %(arg_name, func.__name__))
    3. func(x,y)
    4. z = 1
    5. print('stop')
    6. return
    7. return inner
    return tips

@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))

  1. <a name="Oz0kP"></a>
  2. #### 上下文管理器with
  3. <a name="D88G9"></a>
  4. #### 类
  5. <a name="bUN0U"></a>
  6. #### 在面向对象的编程语言中,“变量”被称作“属性”,“函数”被称作“方法”
  7. <a name="e2f0R"></a>
  8. #### 类的封装:
  9. - 定义给类的属性,通过在属性前加两条下划线的形式,实现:不能通过赋值改变,只能通过类定义的方法改变
  10. ```python
  11. class Player():
  12. def __init__(self, name, hp, occu):
  13. self.__name = name # 把name属性封装
  14. self.hp = hp
  15. self.occu = occu
  16. def print_player(self):
  17. print("玩家 %s 的血量是:%s, 职业: %s" %(self.__name, self.hp,
  18. self.occu))
  19. def rename(self, new_name):
  20. self.__name = new_name
  21. user1 = Player('1', '100', 'war')
  22. user2 = Player('2', '99', 'hunter')
  23. user1.name = '3' # 被封装的name属性不能通过简单的赋值方式来访问
  24. user1.print_player()
  25. user2.print_player()

tips:当需要写多个类时,通常先将每个类都定义出来,但不填充其中的内容,而是将其pass掉,从而厘清逻辑关系

  • 类可以继承
  • 子类直接拥有父类的属性,不需要初始化
  • 如果要重新按照父类的形式,初始化某个属性,给予其不同于父类的默认值,可以使用super()
  • 子类中定义的方法,会覆盖掉父类中的同名方法;即同一个方法,在不同类的实例上,用出来的效果是出不同的,同一个方法有多种的状态,这就叫方法的多态;
  • “多态”和“继承”都是面向对象的编程的特点;
  • 可以通过isinstence(实例, 类)来判断某个实例是否是某个类的子类实例;
  • 实际上在python3中,数字、列表、字符串等都是类;
  • 所有的对象都继承自object类,甚至type()也是;

38. 类的使用-自定义with语句

with open()非常的方便:

  • 跳出with自动关闭,避免忘记写关闭语句的情况

能不能自己实现这种操作呢?
这里open是一个类,在这个类中实现了自动关闭的方法
所以只要自己定义一个类,在定义中实现对应的方法即可
这两个方法分别是__enter__()__exit__()

  1. class Testwith():
  2. def __enter__(self):
  3. print('run')
  4. def __exit__(self, exc_type, exc_val, exc_tb):
  5. print('exit')
  6. with Testwith():
  7. print('test in running')
  8. # 输出结果:
  9. Press ENTER or type command to continue
  10. run
  11. test in running
  12. exit

可以看到,作用就是在开始和结束都做一些“动作”
也可以在退出的时候,自定义处理错误发生的情况:

  1. class Testwith():
  2. def __enter__(self):
  3. print('run')
  4. def __exit__(self, exc_type, exc_val, exc_tb):
  5. if exc_tb is None:
  6. print('nromal exit')
  7. else:
  8. print('has error %s' %exc_tb)
  9. with Testwith():
  10. print('test in running')
  11. raise NameError('test name error')
  12. # 输出结果:
  13. Press ENTER or type command to continue
  14. run
  15. test in running
  16. has error <traceback object at 0x7fa0caaf2d70> # 自定义的错误处理方式
  17. Traceback (most recent call last):
  18. File "with_test.py", line 12, in <module>
  19. raise NameError('test name error')
  20. NameError: test name error
  21. 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’)

  1. ```python
  2. import threading
  3. from threading import current_thread
  4. class Mythread(threading.Thread):
  5. def run(self):
  6. print(current_thread().getName(), 'start')
  7. print('runing')
  8. print(current_thread().getName(), 'stop')
  9. t1 = Mythread()
  10. t1.start()
  11. 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()

  1. <a name="QK4wG"></a>
  2. #### 41. python标准库
  3. - 自带的库就是标准库
  4. - 具体哪些内容,可以去python官方网站看
  5. <a name="U7XgB"></a>
  6. #### 42. 正则表达式库re
  7. <a name="E9lnE"></a>
  8. #### 43. 正则表达式的元字符
  9. - ^$表示空行
  10. - .*?表示不使用贪婪模式
  11. - 在字符串前面加上`r`,可以避免python对字符串中的`\n`等特殊字符进行转义
  12. - `match`与`search`
  13. - `.`任意单个字符
  14. - `*`至少出现1次
  15. - `?`0或1次
  16. - `{m}`出现m次;`{m,n}`出现m到n次
  17. - `[1234]`1234中的任意一个
  18. <a name="oLsqd"></a>
  19. #### 46. 正则表达式的替换函数sub、findall
  20. - `sub`接受3个参数
  21. - 按顺序分别是“正则表达式规则”、“新内容”、“执行替换的原文本”
  22. ```python
  23. import re
  24. phone = '123-456-789 # this is a phone number'
  25. p1 = re.sub(r'#.*$', '', phone)
  26. print(p1)
  27. p2 = re.sub('\D', '', p1)
  28. print(p2)

47. 日期与时间函数库

time``datetime

  1. # import re
  2. # phone = '123-456-789 # this is a phone number'
  3. # p1 = re.sub(r'#.*$', '', phone)
  4. # print(p1)
  5. # p2 = re.sub('\D', '', p1)
  6. # print(p2)
  7. import time
  8. import datetime
  9. print(time.time())
  10. print(time.strftime('%Y-%m-%d'))
  11. print(time.localtime())
  12. print(datetime.datetime.now())
  13. new_time = datetime.timedelta(minutes=10)
  14. print(datetime.datetime.now() + new_time)

48. 数学相关库

math``random

49. 使用命令行对文件和文件夹操作

pwd查看当前所在位置
ls查看当前目录下文件
ls -l获取更多关于当前目录下文件的信息
cd切换到其他目录
cd ..访问上级目录
mkdir建立文件夹;若建立多级文件夹,需要传入参数-p
rmdir g删除文件夹g
rm -rf /tmp/a删除/tmp中的a和下级的所有文件

50. 文件夹操作库os.path、pathlib

51. 机器学习的一般流程和numpy库

机器学习的一般流程

  1. 数据采集
  2. 数据预处理
  3. 数据清洗
  4. 建模
  5. 测试

先安装numpy库pip3 install numpy

55. pandas安装与series结构

58. 层次化索引

层次化索引即多个索引,

  1. import pandas as pd
  2. from pandas import Series, DataFrame
  3. # obj = Series([1, 5, 7])
  4. #
  5. # obj2 = Series([1,2,3], index=[1,2,3])
  6. # print(obj2)
  7. #
  8. # obj2[1] = 100
  9. # print(obj2)
  10. # print(1 in obj2)
  11. #
  12. # sdata = {'beijing':1000, 'shanghai':13132, 'guangzhou':113123}
  13. # obj3 = Series(sdata)
  14. # print(obj3)
  15. data = {'city':['shanghai', 'beijing', 'guangzhou'],
  16. 'year':[2016, 2017, 2018],
  17. 'pop':[1.5, 1.7, 1.9]
  18. }
  19. frame = DataFrame(data)
  20. print(frame)
  21. # 排序
  22. frame2 = DataFrame(data, columns = ['year', 'city', 'pop'])
  23. print(frame2)
  24. # 提取某列的数据
  25. print(frame['city'])
  26. print(frame.year)
  27. # 加列并赋值
  28. frame2['new'] = 100
  29. # 加列并根据表原有数据计算填值
  30. frame2['cap'] = frame2['city'] == 'beijing'
  31. print(frame2)
  32. pop = {'beijing':{2008:1.5, 2009:2.0},
  33. 'shanghai':{2008:1.2, 2009:3.6}
  34. }
  35. # 根据嵌套字典创建dataframe
  36. frame3 = DataFrame(pop)
  37. print(frame3)
  38. # 行列转置
  39. print(frame3.T)
  40. # 重新修改索引,注意重新修改的索引必须是原来就有的,如果没有,会全部填充为nan
  41. obj4 = Series([1,2,4,5], index = ['a', 'b', 'c', 'd'])
  42. obj5 = obj4.reindex(['b','d','c','a','t'], fill_value = 0)
  43. print(obj5)
  44. # 对于缺失值,用相邻的值进行填充
  45. obj6 = Series(['blue', 'purple', 'yellow'], index = [0,2,4])
  46. print(obj6.reindex(range(6), method = 'ffill'))
  47. # 删除缺失的值
  48. from numpy import nan as NA
  49. data = Series([1, NA, 2])
  50. print(data.dropna())
  51. # 删除dataframe的缺失值
  52. data2 = DataFrame([[1., 6.5, 3], [1., NA, NA], [NA, NA, NA]])
  53. # 出现了缺失就丢掉
  54. print(data2.dropna())
  55. # 只有全部缺失才丢掉
  56. print(data2.dropna(how='all'))
  57. # 一整列都缺失才丢掉
  58. data2[4] = NA
  59. print(data2)
  60. # 填充丢失的值为0
  61. print(data2.fillna(0, inplace=True))
  62. print(data2.dropna(axis=1, how='all'))
  63. import numpy as np
  64. data3 = Series(np.random.randn(10),
  65. index = [['a','a','a', 'b', 'b','b','c','c','d','d'],
  66. [1,2,3,1,2,3,1,2,2,4]])
  67. # print(data3)
  68. # print(data3['b'])
  69. # print(data3['b':'c'])
  70. # 将Series类型的数据转化为DataFrame类型的数据
  71. print(data3.unstack())
  72. 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()

```

60. 机器学习分类的原理

用二元一次方程理解

61. TensorFlow的安装

看官网了解更多关于TensorFlow的用法

63. 网页数据的采集与urllib库

from urllib import request

64. 网页请求的常见两种方式

  • get常见的请求方式,给网址传递信息,网址展示出来
  • post登录时,需要传递用户名和密码,此时使用的就是post请求方式

    65. http头部信息的模拟

    66. 使用requests库

    pip3 install requests
    requests库更方便、简单

    67. 结合正则表达式爬取图片链接

    68. BeautifulSoup的安装与使用

    不需要正则 也可提取html语言中的图片
    pip3 install bs4

    69.

    71.

    dbdb模块,字典的持久化储存