Python study notes --- third week

1. file operation
(1) to find the file location
(2) Double-click to open
(3) some operations (r - read (Read) w - write (write) a - added rb - read byte wb - Write Byte ab - Append write r + - reader w + - W R a + - additional read
(4) closes the file
open () - open a file open for opening by a control operating system python
1.1 r pattern
file read only once
format: f = open ( "file location \ filename ", mode =" r "(not written by default r), encoding =" UTF-8 ")
Print (f.read ()) --- all read
print (f.read (11)) - read by character
print (f.readline ()) - reads a line, there is a default trailing newline
print (f.readline () strip () .) - remove newline
print (f.readlines () ) - read row by row, all stored in a list
1.2 path
absolute path: from the disk (C plate) Find
f = open (r "D: \ Python_s25 \ day08 \ t1", mode = "r", encoding = "utf-8")
relative path: to find a file with respect to
f = open ( "t1", mode = "r", encoding = "utf-8")
Path of escape: "E: \ Python full-stack" \ tt telephone - \ t will be considered Tabs
Solution: 1. Each \ become \ "D: \ Python_s25 \ day08 \ T1"
2.E preceded by r --- r "E: \ Python full-stack" r "D: \ Python_s25 \ day08 \ t1" - recommended
1.3 rb mode
byte operation, can not specify the encoding
format: f = open ( "file location \ filename", mode = "rb")
the difference between the r and rb: 1.r need to specify the encoding, not required rb 2.r mode read (3) according to the character reading, RB mode read (3) in bytes read
if the file is large, there will be memory overflow solution: for loop
f = open ( "file location \ filename ", mode =" r "(the default is not written R & lt), encoding =" UTF-. 8 ") for F in Print I (I)
1.4 w mode
w operation - write empty (text) 1. first empty file (file open when empty) 2. write content
when the mode is w and a, there are files on the current file, no file is created file
format: f = open ( "file location \ filename", mode = " W ", encoding =" UTF-. 8 ")
f.write () - write a string to be
1.5 wb - Clear Write (write byte)
A - append write (text)
ab & - Write Append (bytes)
R & lt + - read and write
- Pit use wrong

correct operation: read before write

1.6 w + write read

1.7 a + additional reading

1.8 Other operations
seek () to move the cursor
f.seek (0,0) - the head move the cursor to the file
f.seek (0,1) - Move the cursor to the current position
f.seek (0,2) - move the cursor to the end of the file
f.seek (6) - the cursor is moved in accordance with the byte
tell search cursor

1.9 modify files


test sites


with open advantages: automatically closes the file at the same time multiple files
object file operations 1.10: persistent: permanent storage

2.函数初识
函数:将某个功能封装到一个空间中就是一个函数
目的:减少重复代码
格式 def len():
函数体
len()
2.1 定义函数:
def python中关键字
len 函数名 -- 变量名一模一样
() 必须要写的 格式规定
: 语句结束
len() --函数的调用,函数名+()就是在调用函数
2.2 函数的返回值:
函数的返回值,返回给函数的调用者,return 值 == 返回值
def len()
函数体
return
print(len()
return:
1.可以返回任意类型数据
2.return 返回多个内容是元组的形式
3.return 下方不执行,并且会终止当前这个函数
4.return 不写或写了return后面不写值都返回None
函数名+():
功能:
1.启动函数
2.接受返回值
2.3 函数的参数
形参: 函数定义阶段括号中的参数叫做形参
实参: 函数调用阶段括号中的参数叫做实参
传参: 将实参传递给形参的过程叫传参

形参:
位置参数:
一一对应
默认参数: 函数定义的时括号中写好的就是默认参数
不进行传参使用默认参数,进行传参时使用传递的参数
实参:
位置参数:
一一对应
关键字参数:
按照名字进行传参
混合参数:
位置参数和关键字参数一起使用

            位置参数 > 默认参数(关键字参数)
    2.4 三元运算
            a = 6
            b = 9
            c = a if a > b else b
            print(c)
            条件成立的结果(a) 条件(if a > b else) 条件不成立的结果(b)

3.函数的动态参数
动态位置参数


动态关键字参数

位置参数>动态位置参数>默认参数>动态默认参数
万能传参

*args(聚合位置参数)      大家伙都用的名字, 可以进行修改但是不建议修改
**kwargs(聚合关键字参数) 大家伙都用的名字, 可以进行修改但是不建议修改

函数的定义阶段 * 和 ** 都是聚合
函数体中 * 就是打散, *args将元组中的元组进行打散  *kwargs将字典的键获取

形参:
   位置参数:
   动态位置参数: 先执行位置参数,位置参数接受后额外的参数动态位置参数进行接受 获取的是一个元组
    默认参数:
动态关键字参数(默认): 先执行默认参数,默认参数接受后额外的默认参数动态默认参数进行接受,获取的是一个字典

 实参和函数体:
   * 打散
   ** 实参时能够使用

4.函数的注释

print(b.__doc__) 查看函数的注释
print(a.__name__) 查看函数的名字

5.名称空间
分类:
内置空间 : Python解释器自带的空间
全局空间 : py文件中顶格写的就是全局空间
局部空间 : 函数体中就是局部空间
加载顺序:
内置空间
全局空间
局部空间
取值顺序
局部空间
全局空间
内置空间
作用域
全局作用域:全局空间+内置空间
局部作用域:局部空间
6.函数的嵌套和 global 和 nonlocal
函数嵌套:不管在什么位置,只要是函数名()就是在调用一个函数
global : 只修改全局,如果全局没有就创建一个新的
nonlocal :只修改局部,修改离声明nonlocal 最近的一层,上一层没有继续向上上层查找,只限在局部,找不到就报错
7.函数名的第一类对象及使用
函数名可以当作值,赋值给变量

函数名可以当作容器中的元素

函数名可以当作函数的参数

函数名可以当作函数的返回值

8.f - strings
f"{变量名}"
F"{变量名}"
f"""{变量名}"""
f"{input()}"
f"{3 if 3>2 else 2}"
lst = [1,2,3,4,5]
f"{lst[4]}"
f"{lst[-1]}"
f"{dic['key1']}"

9.迭代器
可迭代对象:只要具有__iter__() 方法就是一个可迭代对象
list,tuple,str,set,dict 取值方式只能直接看
迭代器:工具 具有__iter__()和__next__()两个方法才是迭代器
lst = [1,2,3,4,5]
l = lst.__iter__() # 将可迭代对象转换成迭代器
l.__iter__() # 迭代器指定__iter__()还是原来的迭代器
print(l.__next__()) # 1
print(l.__next__()) # 2
for 循环的本质
while True:
try:
print(l.__next__())
except StopIteration: #当循环发生错误时终止循环
break
iter() 和 iter() 是一样的 推荐使用iter()
python3 和 python2的区别:
python3:
iter()和 iter() 都有
next()和__next__()都有
python2:
iter()
next()
迭代器优点:
惰性机制 -- 节省空间
迭代器缺点:
不能直接查看值 迭代器查看到的是一个迭代器的内存地址
一次性,用完就没有了
不能逆行(后退)
空间换时间: 容器存储大量的元素,取值时 取值时间短,但是容器占用空间较大
时间换空间: 迭代器就是,节省了空间,但是取值时间较长
迭代器是基于上一次停留的位置,进行取值

10.生成器
核心: 生成器的本质就是一个迭代器
生成器的作用是节省空间
生成器和迭代器的区别:
迭代器python自带的
生成器程序员自己写的一种迭代器
生成器编写方式:
基于函数编写
推导式方式编写


函数体中出现yield代表要声明一个生成器
一个yield 对应一个 next

yield 和 return 的区别
相同点:
1.都是返回内容
2.都可以返回对个,但是return写多个只会执行一个
不同点:
1.return 终止函数 yield是暂停生成器
2.yield能够记录当前执行位置
可迭代对象:
优点: list,tuple,str 节省时间,取值方便,使用灵活(具有自己私有方法)
缺点: 大量消耗内存
迭代器:
优点:节省空间
缺点:不能直接查看值,使用不灵活,消耗时间,一次性,不可逆行
生成器:
优点:节省空间,人为定义
缺点:不能直接查看值,消耗时间,一次性,不可逆行
使用场景:当文件或容器中数据量较大时,建议使用生成器

    数据类型 (pyhton3: range() | python2 :xrange()) 都是可迭代对象 __iter__()
    文件句柄是迭代器  __iter__() __next__()

    区别什么是迭代器,什么是生成器

            迭代器的地址 <list_iterator object at 0x000000987B6E97F0>
            生成器的地址 <generator object func at 0x00000087C2A10CA8>
            没有send方法就是一个迭代器,具有send方法的就是一个生成器
    send
        ![](https://img2018.cnblogs.com/blog/1754444/201908/1754444-20190817115618533-2023116577.png)
        ![](https://img2018.cnblogs.com/blog/1754444/201908/1754444-20190817115627148-1479110562.png)
    yield 和 return 的区别
     相同点:
        1.都是返回内容
        2.都可以返回对个,但是return写多个只会执行一个
     不同点:
        1.return 终止函数 yield是暂停生成器
        2.yield能够记录当前执行位置
     一个yield 对应一个 next
    yield from 和 yield 的区别
           yield from 将可迭代对象中的元素逐个返回
           yield 一次性返回

11.推导式
列表推导式:
普通循环
print([i for i in range(10)])
print([变量 for循环])
筛选模式
print([i for i in range(10) if i % 2 ==0])
[加工后的变量 for循环 加工条件]
集合推导式:
普通循环
print({i for i in range(10)})
{变量 for循环}
筛选模式
print({i for i in range(10) if i % 2 == 1})
{加工后的变量 for循环 加工条件}
字典推导式:
普通循环
print({i: i+1 for i in range(10)})
{键:值 for循环}
筛选模式
print({i: i+1 for i in range(10) if i % 2 == 0})
{加工后的键:值 for循环 加工条件}
生成器推导式:
普通模式
tu = (i for i in range(10))
( 变量 for循环)
筛选模式
tu = (i for i in range(10) if i > 5) (加工后的变量 for循环 加工条件)
12.内置函数一:
eval() -- 执行字符串里的内容,并返回最终结果(神器一)

    exec() -- 执行字符串里的内容,并返回最终结果(神器二)

     以上两个禁用

     hash() -- 获取一个对象(可哈希对象:int,str,Bool,tuple)的哈希值

           作用就是区分可变数据类型和不可变数据类型

     help() -- 查看帮助信息

     callable() -- 查看对象是否可调用

      int() -- 用于将一个字符串或数字转换为整型

     float() -- 函数用于将整数和字符串转换成浮点数

     complex() -- 复数

     bin() -- 十进制转二进制

     oct() -- 十进制转八进制

     hex() -- 十进制转十六进制

     divmod(除数,被除数) -- 求商和余数

     round(3.6567,2) -- 指定保留的小数位数

     pow(2,2) -- 两个参数是求幂

     pow(2,2,3) -- 三个参数是求幂后的余

     bytes(s,encoding="utf-8") -- 将字符串进行编码

     repr() -- 查看数据的原生态(给程序员使用的)

       print() -- 给用户使用的

     all() -- 判断容器中的元素是否都为真,类似于and

     any() -- 判断容器中的元素是否有一个为真,类似于or

     locals() -- 查看当前空间变量

     globals() -- 查看全局空间变量

Guess you like

Origin www.cnblogs.com/sunyongchao/p/11368122.html