python初学随记

语言特点:开源、跨平台,扩展性强、类库多
主流开发工具:pycharm
学习版本:python3.6.5

基础:
注释用“#”
基本数据类型(4种):
整数 int
浮点数float
字符串str
布尔值bool (True、False)

序列(3种):
字符串
列表[1, 2, 3] 存储的内容可以变更 增加append() 移除remove()
元组(“1”, “2”, “3”)存储的内容不可以变更
序列的基本操作 成员关系in / not in 连接+ 重复* 切片[:]
了解方法: filter() list() len()

字典
{1:2, 2:3, 3:4}

分支
if 表达式:
xxx
elif 表达式:
xxx
else:
xxx
了解方法:input() 接受用户输入

循环
while 表达式:
循环内容
for 迭代变量 in 可迭代对象:
循环内容

break\continue
range(startNum,endNum)
time.sleep(1)

与操作:and
列表推导式: [i *i for i in range(1,11) if i%2 ==0]
字典推导式:{i : 0 for i in [1,2]}

文件操作
file1 = open(“a.txt”, “w/r”) 打开文件
file1.read() 输入
file1.readLine() 输入一行 readLines()逐行读取
file1.seek() 读取位置移动
file1.tell() 当前指针位置
file1.write(‘hello world’) 输出
file1.close() 关闭文件

import datatime
datetime.datetime.now()

异常
try:
监控代码
except Exception [reason]
异常处理
finally:
都会执行

函数
def 函数名(参数):
函数体
return 返回值
import re
re.findall(‘a’,“abc”)
关键字参数 print(“1111”, end = “a”)
可变长参数 def func(first, *other)

变量作用域:
默认同一个变量在函数外有一个作用域,在函数内有另一个作用域,互不干扰
要保持统一需要在函数内部声明变量global var 变成全局变量,之后再去改变变量的值
迭代器方法 iter()、next()
生成器关键字: yield 运行到yield会暂停并且记录当前值,在此运行会从记录的值开始

lambda表达式
lambda 参数:返回值表达式

内建函数
filter(function,iterable) 过滤iterable中满足条件function,可以用list()转换结果
map(function,*iterable) 对iterable中的元素进行function操作,可以用list()转换结果
reduce(function,sequence[, initial]) 对iterable中的元素 依次进行function操作
from functools import reduce
a = [1, 2, 3, 4, 5, 6, 7]
print(reduce(lambda x, y: x * y, a, 2))

zip(iter1 [,iter2 […]]) 对iter1进行合并

闭包:内部函数引用外部函数的变量
装饰器: 内部函数引用外部函数的变量作为函数调用
可以多层嵌套函数
上下文管理器:with

模块导入方式:
import mode
import mode as m
from mode import func

编码规范 PEP8, pycharm可以添加扩展工具Autopep8

类的定义
class 类名’()’:
def init (self):
xxxx
def print_desc(self, a, b)
self每个方法里都要有,如果属性不被外部访问要使用用__开头
pass 可以先不写类的实现,同时不会报错
isInstance(1,object) 判断1是否是object的类型
with 语句会在初始时候调用函数的 enter(self)方法 结束会调用函数的__exit__()方法
累的继承 class A(B)

多线程编程:
threading Queue
实现函数在线程里调用:
t = threading.Thread(target = 方法名,args = (参数…))
t.start()
t.join() 在主线程之前调用
用自定义线程子类:
class myThread(threading.Thread):
def fun(self):

Python中常用的标准库
re: 文字处理
time\datetime 日期类型
math\random 数字和数学类型
pathlib\os.path 文件和目录访问
tarfile 数据压缩和归档
os\logging\argparse 通用操作系统
threading\queue 多线程
base64\json\urllib Internet数据处理工具
unitest 开发工具
timeit 调试工具
venv 软件包发布
main 运行服务
日期与时间库 time datetime
数学相关库 math random
文件夹操作库 os pathlib

正则表达式:
t = re.compile(‘ca*t’) 匹配的字符
t.match(‘caaaaaat’) 要匹配的字符
t.search(‘caaaaaat’) 要搜索的字符
re.sub(‘被替换的c’,‘替换为d’,‘原串’) 替换
. 匹配一个字符,可以…
^ 匹配开头的字符
$ 匹配结尾的字符

  • 出现0次或者多次字符
    +出现1次或者多次字符
    ?出现0次或者1次
    {n} 出现n次
    {n,m} 出现n次到m次
    [] 匹配指定字符
    \d 匹配数字
    \D 非数字
    \s 空白字符
    () 分组
    | 左右
    ^¥空行
    .*? 不使用贪婪模式
发布了5 篇原创文章 · 获赞 12 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/u010823943/article/details/104143336