轻松玩转AI路径:
- 从Python开始 [链接]
- 数据科学 [链接]
- 机器学习 [链接]
- 深度学习——神经网络 [链接]
从Python开始:
Python3入门 目录:
1. 简介
Python的特点:简洁
Python是面向对象的语言:
- 把现实解释中各种各样事物的关系和特征映射到计算机中。
Python适合的领域:
- 爬虫
- 大数据与数据分析
- 自动化运维与自动化测试
- Web开发
- 机器学习
- 作为“胶水”语言把其他语言开发的模块包装来方便使用
Python不适合的领域:
- 贴近硬件的代码(首选C)
- 移动开发:iOS/Android有各自的开发语言(ObjC,Swift/Java)
- 游戏开发:C/C++
Python和其他语言对比:
2. 数据类型
- 不可变类型(值类型):数字、字符串、元组
可变类型(引用类型):列表、集合、字典
type(Data) 可查询数据类型函数
- isinstance(对象, [数据类型1, 数据类型2]) 可判断对象是否是数据类型1…
1. 数字:Number
- 不可变类型(值类型)
- 整数:int
- 浮点数:float
0b开头为二进制,bin(Number) 转换为二进制
0o开头为八进制,oct(Number) 转换为八进制
0x开头为十六二进制,hex(Number) 转换为十六进制
int(Number) 转换为十进制
- Bool 布尔类型:表示真(True)、假(False)
真表示数字:1
假表示数字:0
bool(Number):Number 为0或空或None则假(False),非0或非空则真(True)。
- complex:复数
2. 组
1) 序列
(1) 字符串:str
- 用
单引号(' ')、双引号(" ")、三引号(''' '''/""" """)
表示字符串。 - 字符串可以为空
- 字符串是有序序列,可用下标索引来访问、切片操作
不可变类型(值类型)
转义字符:\
- 特殊的字符。
- 无法“看见”的字符。
- 与语言本身语法有冲突的字符。
转义字符符号 说明 \n 换行 \’ 单引号 \t 横向制表符 \r 回车 原始字符串:r
[1] 字符切片
- 每个字符均有从头部 0开始增大的索引,或从尾部 -1开始减少的索引。
例:
>>> "hello work"[0]
"h"
>>> "hello work"[-1]
"k"
>>> "hello work"[:]
"hello work"
>>> "hello work"[1:]
"ello work"
>>> "hello work"[1:3]
"el"
>>> "hello work"[1:-3]
"ello w"
>>> "hello work"[:-3]
'hello w'
[2] 字符运算
例:
>>> "hello work" + "s"
"hello works"
>>> "hello work"*3
"hello workhello workhello work"
字符运算无减法、除法,乘法只能乘以整数。
(2) 列表:list
- 列表的表示方式:[ ]
- 列表可包含 数字、字符、组
- 列表可以为空
- 列表是有序序列,可用下标索引来访问、切片操作
- 可变类型(引用类型)
例:
["hello",2,True,[1,2],[True,False]]
# 列表可嵌套
[1] 列表切片
- 每个列表中的元素均有从头部 0开始增大的索引,或从尾部 -1开始减少的索引。
例:
>>> ["hello", "work", "i", "love"][0]
"hello"
# 单一取元素索引
>>> ["hello", "work", "i", "love"][0:2]
["hello", "work"]
# : 则取元素列表
>>> ["hello", "work", "i", "love"][-1:]
["love"]
[2] 列表运算
例:
>>> ["hello", "work", "i", "love"] + ["you"]
["hello", "work", "i", "love", "you"]
>>> ["you"] * 3
["you", "you", "you"]
列表运算无减法、除法,乘法只能乘以整数。
(2) 元组:tuple
- 元组表示方式:( )
- 单一元素的元组需加 , 逗号
- 元组可包含 数字、字符、组
- 元组可以为空
- 元组是有序序列,可用下标索引来访问、切片操作
- 不可变类型(值类型)
例:
>>> (1,2,3,4,5)
(1,2,3,4,5)
>>> (1,)
(1)
>>> ()
()
[1] 元组切片
- 每个元组中的元素均有从头部 0开始增大的索引,或从尾部 -1开始减少的索引。
例:
>>> (1,"-1",true)[0]
1
# : 则取元素元组
>>> (1,"-1",True)[0:2]
(1,"-1")
[2] 元组运算
例:
>>> (1,"-1",true)+(4,5)
(1,"-1",true,4,5)
# : 则取元素元组
>>> (1,"-1",true)*3
(1,"-1",true,1,"-1",true,1,"-1",true)
元组运算无减法、除法,乘法只能乘以整数。
2) 集合:set
- 定义空集合方式:set()
- 集合是无序,没有索引,没有切片
- 集合内所有元素类型要相同
- 集合自动去重
- 可变类型(引用类型)
例:
>>> {1, "hello"}
{1, "hello"}
(1) 集合运算
- 差集:-
例:
>>> {1,2,3,4,5,6} - {3,4}
{1,2,5,6}
- 交集:&
例:
>>> {1,2,3,4,5,6} & {3,4}
{3,4}
- 并集:|
例:
>>> {1,2,3,4,5,6} | {3,4,7}
{1,2,3,4,5,6,7}
4) 字典:dict
- 字典的表示方式:{ }
- 字典由键值对组成,即 key:value
- 字典是无序,没有索引、切片操作
- 通过 key 访问 value
- key 不能重复,必须为不可变类型(数字、字符串、元组)
- value 可以是 数字、字符串、组
- 可变类型(引用类型)
例:
>>> {"2":"hello","1":"work",1:"love"}["1"]
work
>>> {"2":"hello","1":"work",1:"love"}[1]
love
3. 变量、表达式、运算符
1) 变量
- 赋值语句:变量 = 值
- 变量名可包含字母、数字、下划线,首字母不能为数字
- 变量名区分大小字
- 变量名不能用系统关键字(保留字)
2) 表达式
- 表达式(Expression)是运算符(operator)和操作符(operand)所构成的序列。
3) 运算符
运算符同一级别则按 表达式 从左向右
运算
4. 流程控制语句
- 条件、循环、分支、枚举
条件、循环、分支、枚举 皆可互相嵌套使用
- continue 跳出后继续执行
- break 强制结束控制语句
1) 条件语句
- if elif else
if 条件判断1: # True
执行语句1
elif 条件判断2: # True
执行语句2
else: # 非真值条件
pass # pass 空语句/占位语句
# if elif 只执行其中一个
2) 循环语句
- while else
- for else
a = True
while a:
执行语句
# 死循环
b = 1
while b <= 10:
b += 1
执行语句1
# 执行10次
else: # while 返回False时执行
执行语句2
# 主要是用来遍历/循环、序列或者集合、字典
for 新变量x in 可迭代对象:
执行语句1
print(x)
else: # for 结束后执行
执行语句2
5. 组织结构
- 包
- 模块
- 类
- 函数、变量
- 类
- 模块
包:文件夹
模块:.py 文件
命名空间:包名.模块名
引用/导入:
# 同一路径下 import 模块名 # 不同路径下 import 包名.模块名 或 import 包名.模块名 as 新名 # 导入模块 from 包名 import 模块 # 导入模块内具体的函数/变量 from 包名.模块名 import 函数名/变量名 # 全部导入模块内所有的函数/变量 from 包名.模块名 import *
包和模块不会被重复导入。
1) 包
定义包:在包内建 __init__.py 文件。
(1) _init_.py
__init__.py 文件在包被使用时会自动加载。
# 自动加载模块:
__all__ = ['模块名1','模块名n']
2) 函数
(1) 函数的特性:
- 功能性
- 隐藏细节
- 避免编写重复的代码
(2) 函数基本结构
def funcname(parameter_list):
pass
funcname(parameter_list) # 函数调用
# 1. parameter_list 参数列表可以没有
# 2. 可使用 return value 来返回结果,否则返回 None
例:
def add(x, y=0): # y=0 为无传参时默认 y=0
result = x + y
q = 4
return result, q # 多个则返回元组
print('ok') # 不会被执行
def print_code(code):
print(code)
a = add(1, 2)
b = print_code('python') # 赋值时函数被调用执行
print(a, b)
# 返回:
# python
# (3, 4) None
p1_add, p2_add = add(3, 4) # 序列解包
print(p1_add, p2_add)
# 返回:
# 7 4
序列解包例:
d = 1, 2, 3 # 生成元组
a, b, c = d # 序列解包,数量需要相同
# 等同于 a, b, c = [1, 2, 3]
(3) 函数参数
- 必须参数:形参、实参
- 关键字参数
- 默认参数
例:
def add(x, y=0): # x,y 为形式参数(形参);y=0 为无传参时默认为0(默认参数)
result = x + y
return result
a = add(1, 2) # 1,2 为实际参数(实参)
b = add(y=3, x=4) # y=3, x=4 为关键字参数
6. 面向对象
- 核心:类、对象
1) 类:class
变量代表刻划类的特征,方法代表类的行为。
- 类最基本的作用:封装
- 类名首字母大写
- 类名不建议使用 _ 下划线 分隔,建议使用小驼峰法(即每个不同的单词首字母大写)。
class StudentRoom():
def print_file(self):
print('name:' + self.name)
student = StudentRoom() # 实例化
student.print_file() # 调用类的方法
(1)类的 方法 和 函数 的区别
- 方法:设计层面 (更多是面向对象)
- 函数:程序运行、过程式的一种称谓 (更多是面向过程)
- 变量:存在于模块内,一般称为 变量;而存在于类内,一般称为 数据成员。
(2) 类 和 对象 的关系和区别
类 是现实世界或思维世界中的实体在计算机中的反映,它将数据以及这些数据上的操作封装在一起。(抽象概念)
类面向对象设计最重要是:行为 与 特征
- 要找对主体,即类内的 函数 作用要相似或一致。
对象 是用来表示一个具体的概念。当 类 被实例化后就成为一个具体的对象,并需要传递具体的数据。
类就像是一个模板,通过类可以产生很多的对象。
2) 类的构造函数
- 构造函数可以生成不同的对象
- 类被实例化后构造函数会自动被调用
class StudentRoom():
def __init__(self): # 构造函数。
pass
student = StudentRoom() # 实例化
3) 类变量、实例变量、实例方法、类方法、静态方法
class StudentRoom():
name = '1' # 类变量
sum = 0
# 有self则为 实例方法,代表实例。
def __init__(self, name, age):
# 构造函数初始化对象的属性
self.name = name # 实例变量,保存特征值
print(self.__class__.name) # 打印类变量。
@classmethod # 类方法。装饰器
def plus_sum(cls):
cls.sum += 1
print(cls.sum)
@staticmethod # 静态方法。装饰器
def add(x, y):
print('This is a static method')
student = StudentRoom('小兔', 20) # 创建对象
print(student.name) # 返回 小兔
print(StudentRoom.name) # 返回 1
# __dict__ 保存着所有实例变量
print(student.__dict__) # 返回 {'name':'小兔'}
# 调用 类方法
StudentRoom.plus_sum()
# 调用 静态方法
StudentRoom.add(1,2)
类方法和静态方法不能访问实例变量
4) 类的成员可见性
- 公开成员、私有成员
- 私有成员外部无法访问
class Student():
def __init__(self, name):
self.name = name
self.__score = 0 # 含 __ 则为私有变量
def marking(self, score):
if score < 0:
return '负数不合法'
self.score = score
print(self.name + str(self.score))
def do_homework(self):
self.do_english_homework() # 内部调用
print('homework')
def __do_english_homework(self): # 含 __ 则为私有方法
print()
student = Student('小兔')
student.marking(90) # 保证数据安全 # 返回 小兔90
student.do_english_homework() # 外部调用
student.__score = -1 # 此非原有类中的私有变量,而是增加新的私有变量。
print(student.__dict__)
print(student._Student__score) # 间接访问私有变量
5) 面向对象3大特性
- 继承性、多态性、封装性
(1) 继承性
- 作用:避免定义重复的方法、重复的变量。
class Human():
sum = 0
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
print(self.name)
# Student类 继承 Human类。
# Human是Student的父类,Student是Human的子类。
class Student(Human):
def do_homework(self):
print('english homework')
# 子类继承了父类的所有,所以可以调用
student1 = Student('石敢当', 18)
print(Student.sum, student1.sum, student1.name)
student1.get_name()
class Human():
def __init__(self, name, age):
self.name = name
self.age = age
def do_homework(self):
print('This is a parent method')
class Student(Human):
# 在父类的基础上增加属性
def __init__(self, school, name, age):
self.school = school
# 传参给父类
super(Student, self).__init__(name, age)
# 和父类同名时,优先调用子类的方法,所以需加super
def do_homework(self):
super(Student, self).do_homework()
print('english homework')
student1 = Student('人民路小学', '石敢当', 18)
print(student1.sum, student1.name)
student1.do_homework()
7. 正则表达式
1) 正则表达式
- 正则表达式是一个特殊的字符序列,一个字符串是否与我们所设定的这样的字符序列相匹配。
- 快速检索、实现一些替换文本的操作。
- 如检查一串数字是否电话号码
- 如检测一个字符串是否符合email
- 如把一个文本里指定的单词替换为另外一个单词
a = 'C|Python'
print(a.index('Python')>-1)
print('Python' in a)
# 均返回 True
# 使用正则表达式匹配
import re
r = re.findall('Python', a)
if len(r) > 0:
print(ok)
print(r) # 返回 ['Python']
8. 枚举类型
- 枚举是一个类
- from enum import Enum
- 枚举类型不能被更改
- 枚举类型不能有相同标签(常量不能相同)
- 枚举不返回值
- 枚举类型不能实例化,属于单例模式
1) 区别
# 方法1:
yellow = 1
green = 2
# 方法2:
a = {'yellow':1, 'green':2}
# 方法3:
class TypeDiamond():
yellow = 1
green = 2
以上方法的缺点:
可变
没有防止相同标签的功能
from enum import Enum # 枚举类
class VIP(Enum):
YELLOW = 1
GREEN = 2
BLACK = 1 # 值相同时,BLACK相当于YELLOW的别名,即YELLOW_ALIAS
print(VIP.YELLOW) # <enum 'VIP'>
# 返回: VIP.YELLOW
print(VIP.BLACK)
# 返回: VIP.YELLOW
print(VIP['YELLOW'])
# 返回: VIP.YELLOW
print(VIP.YELLOW.value)
# 返回: 1
print(VIP.YELLOW.name) # <class 'str'>
# 返回: YELLOW
for v in VIP:
print(v)
# 返回:(别名枚举不会被遍历)
# VIP.YELLOW
# VIP.GREEN
for v in VIP.__members__:
print(v)
# 返回:
# YELLOW
# GREEN
# BLACK
for v in VIP.__members__.items():
print(v)
# 返回:
# ('YELLOW',<VIP.YELLOW: 1>)
# ('GREEN',<VIP.YELLOW: 2>)
# ('BLACK',<VIP.YELLOW: 1>)
2) 枚举比较
- 枚举类型能做 等值比较、身份比较,不能做 大小比较。
from enum import Enum
class VIP(Enum):
YELLOW = 1
GREEN = 2
result1 = VIP.GREEN == VIP.YELLOW
print(result1) # 返回:False
result2 = VIP.GREEN == 2
print(result2) # 返回:False
result3 = VIP.GREEN is VIP.GREEN
print(result3) # 返回:True
class VIP1(Enum):
YELLOW = 1
GREEN = 2
result = VIP.GREEN == VIP1.GREEN
print(result) # 返回:False
from enum import Enum
class VIP(Enum):
YELLOW = 1
GREEN = 2
a = 1
# 变成枚举类型,并非真正的类型转换
print(VIP(a)) # 返回:VIP.YELLOW
from enum import IntEnum # 必须是数字
from enum import unique
@unique # 不允许值重复
class VIP(IntEnum):
YELLOW = 1
GREEN = 2
函数式编程:
- 命令式编程:如 def 、if else、for …
- 函数式编程:如 map、reduce、filter、lambda …
9. 闭包
- 闭包 = 函数 + 环境变量(函数定义时候)
例:
def curve_pre():
a = 25 # 环境变量
def curve(x):
return a*x*x
return curve
a = 10
f = curve_pre()
print(f(2)) # 返回: 100
def f1():
a = 10
def f2():
a = 20
print(a) # 返回: 20
print(a) # 返回: 10
f2()
print(a) # 返回: 10
f1()
# 返回:10 20 10
# 改变全部变量的方法:
origin = 0 # 全局变量
def go(step):
global origin
new_pos = origin + step
origin = new_pos
return new_pos
print(go(2)) # 返回: 2
print(go(3)) # 返回: 5
print(go(6)) # 返回: 11
# 闭包的方法:
origin = 0
def factory(pos):
def go(step):
nonlocal pos
new_pos = pos + step
pos = new_pos
return new_pos
return go
tourist = factory(origin)
print(tourist(2)) # 返回: 2
print(tourist(3)) # 返回: 5
print(tourist(6)) # 返回: 11
print(origin) # 返回: 0
10. 匿名函数
- 不定义函数名的函数。
lambda 表达式:
lambda parameter_list: expression
例:
def add(x, y):
return x + y
add(1, 2)
# 等同于:
f = lambda x,y: x+y
f(1, 2)
三元表达式:
条件为真时返回的结果 if 条件判断 else 条件为假时的返回结果
例:
x = 2
y = 1
r = x if x > y else y
print(r) # 返回:2
map 类:
- 把一个集合里的元素映射到新的集合里。
list_x = [1,2,3]
def square(x):
return x * x
r = map(square, list_x)
# 等同于:
#for x in list_x:
# square(x)
print(list(r)) # 返回:[1,4,9]
list_x = [1,2,3]
r = map(lambda x: x*x, list_x)
print(list(r)) # 返回:[1,4,9]
list_x = [1,2,3,4,5]
list_y = [1,2,3]
r = map(lambda x,y: x*x+y, list_x, list_y)
print(list(r)) # 返回:[2,6,12]
reduce 函数:
- 连续计算,连续调用 lambda,每一次的计算结果作为下一次计算的参数。
from functools import reduce
list_x = [1,2,3,4]
r = reduce(lambda x,y: x+y, list_x)
print(r) # 返回:10
# ((1+2)+3)+4
r = reduce(lambda x,y: x+y, list_x, 10) # 10为初始值
print(r) # 返回:20
# (((10+1)+2)+3)+4
filter 类:
- 过滤器
list_x = [1,0,1,0,0,1]
filter(lambda x: True if x==1 else False, list_x)
print(list(r)) # 返回:[1,1,1]
11. 装饰器
- 在不修改原函数代码的情况下,增加功能。
- 装饰器符号:@
- 一个函数可以增加多个装饰器
例:
import time
def f1():
print('This is a function')
# 在不修改原函数的情况下,增加打印时间戳
def print_current_time(func):
print(time.time())
func()
print_current_time(f1)
import time
# 装饰器
def decorator(func):
def rint_current_time():
print('123')
func()
return rint_current_time
def f1():
print('This is a function')
f = decorator(f1)
f()
import time
# 装饰器
def decorator(func):
# * 为可变参数, ** 为关键字参数
def rint_current_time(*args, **kw):
print(time.time())
func(*args, **kw)
return rint_current_time
# 装饰器名字
@decorator
def f1(func_name, **kw):
print('This is a function')
f1('test func', a=1, b='2')
注:资料整理来源于:https://www.imooc.com/