Python_集合与运算/文件读写、修改详解/字符编码详解/函数和函数式编程/函数式编程之参数/局部变量与全局变量/递归/高阶函数
在这里得感谢,老师Alex金角大王(路飞学城IT)
Python(给兄弟们挂个🔗)
>_<…因为有的是自己理解,如有错误,希望大家踊跃评论,我好即使改正…
一、集合:
集合是一个无序的、不重复的数据组合,主要作用:
1.去重(列表变集合,自动去重)
2.关系测试,测试两个集合的交集、差集、并集等关系
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#主要作用1.去重,把一个列表变成集合,就自动去重了
#2.关系测试list_1 = [1,4,5,7,3,6,7,9]
list_1 = set(list_1)
list2 = set([2,6,0,66,22,8,4])
print(list_1,type(list_1))#集合是无序的
print(list2)
#交集
q = list_1.intersection(list2)
print(q)
#并集
print(list_1.union(list2))
#差集....我这有你那边没有的..in list_1 but not in list2
print(list_1.difference(list2))
print(list2.difference(list_1))
#子集 subset or upperset
list_3 = set([1,3,7])
print(list_3.issubset(list_1))#is sub set(子集)
print(list_1.issuperset(list_3))#iss uper set(父集)#对称差集
print(list_1.symmetric_difference(list2))#两个并集,再把"交集"去掉..print("-----------")
list_4 = set([5,6,8,7])
print(list_3.isdisjoint(list_4))#判断有无交集....有交集是Flaser..."7"#用运算符 表示
print(list_1&list_4)# "&" 交集 intersection
print(list_1|list_4)# "&" 并集unition
print(list_1 - list_4)# "差集" 差集difference
print(list_1^list_4)# "对称差集" 对称差集symmetric_difference....两个并集,再把交集删掉#增
list_1.add(999)
list_1.update([888,777,555])
#删
list_1.remove(999)
list_1.discard(999)
list_1.pop()#这里指定不了....这里是随机删除print(list_1,len(list_1))
#查
print(888 in list_1)#在不在集合里
(1)列表变成"集合":
student = [1,2,3,4,4,5,6]student_1 =set(student)
student_2 = set([1,9,8,5,7])print(student_1,student_2,type(student_1))
result:
{1, 2, 3, 4, 5, 6} {1, 5, 7, 8, 9} <class ‘set’>…实现了"去重"的功能…
(2)“交集”、“并集”、“差集” 和 “子集”:
“交集”:
q = student_1.intersection(student_2)
print(q)
并集":
print(student_1.union(student_2))
差集":
print(student_1.difference(student_2))#我有的你没有...
print(student_2.difference(student_1))
result:
{2, 3, 4, 6}
{8, 9, 7}
“对称差集”:
print(student_1.symmetric_difference(student_2))#先并集...再去交集...
“子集” 和 “父集”:
student_3 =set([2,3])
print(student_1.issuperset(student_3))#父集关系
print(student_3.issubset(student_1) )#子集关系
result:
True
True
"判断"有无交集…有,返回True…
print(student_1.isdisjoint(set([1.2,8,100])))
result:
True
用运算符表示"关系测试":
#用运算符 表示
print(list_1&list_4)# "&" 交集 intersection
print(list_1|list_4)# "&" 并集unition
print(list_1 - list_4)# "差集" 差集difference
print(list_1^list_4)# "对称差集" 对称差集symmetric_difference....两个并集,再把交集删掉
(3)集合的"增"、“删”、“改” 和 “查”:
“增”:
student_1.add(100)
student_1.update([8,9])
print(student_1)
result:
{1, 2, 3, 4, 5, 6, 100, 8, 9}…注:这里不能赋值给变量再输出…
“删”:
student_1.remove(100)
student_1.discard(9)
student_1.pop()#随机删除...
print(student_1)
result:
{2, 3, 4, 5, 6, 8}
“查”:
#查
print(8 in student_1)#在不在集合里
conclude:
True
conclude:
add/updata/remove/discard…
二、文件操作:
(1)先创建一个文本文件:
(2)文件操作:
1.打开文件…将文件句柄赋值给一个变量…
2.通过文件句柄,对文件操作
3.关闭文件
1."只读"文件操作:
f = open('yester2','r',encoding = "utf - 8")
print(f.read())
f.close
result:
1.当前文件夹里打开…'gdk’是windows打开形式…'utf-8’则是python打开方式
2.f.read()…此时已经全部读完,光标移动到最后一个…
2."重新写"文件操作:
f = open('yester2','w',encoding = "utf - 8")
print(f.write("我爱北京天安门"))
f.close
result:
1.若原文件有内容…把之前的内容删除重写…
3."追加写"文件操作:
f = open('yester2','a',encoding = "utf - 8")
print(f.write("1234679"))
f.close
result:
1.不删除原文件内容…在后面"追加"编辑新内容
4."只读几行"的文件操作:
#只想只读前5行
f = open("yester2",'r',encoding = "utf-8")
print(f.readline())
print(f.readlines())#把 所读的文件内容 变成"列表"
result:
1.readline,是只读文件一行
2.readlines,从"光标"之后,全部读完 “每一行” ,所有行存在一个 “列表” 里
(1)低级操作:
for i in range(2):print(f.readline())
for line in f.readlines():print(line)
"替换"操作:
for index,line in enumerate(f.readlines()):if index == 2 :print('-------我是分割线--------- ')continueprint(line.strip())
这种用readlines 的转成"列表",非常占内存,一般不用…
(2)高逼格:
count = 0
for line in f:if count ==9:print('-------------')count += 1continueprint(line.strip())#这个时候...执行是一样的.只保存一行count += 1
conclude:
1.for i in range ( ): >>> print(f.readline())
2. for line in f.readlines(): >>> print(line) ; for index,iteam in enmurate(f.readlines)
3. for line in f ; >>> print (line.strip())!!!
5.文件光标操作:
print(f.tell())#返回"现在"光标
f.read(5)
f.seek()#光标回到‘0’
print(f.seekable)#判断是否可以返回
6.文件“刷新”:
print(f.flush())#每写完一行..不会刷到硬盘里#堆积成缓存文件..够一定大小..一次性再存到硬盘里
#确认"写的东西"要写在硬盘里
print(f.flush())#强制刷新
附(进度条):
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-......stdout/sydin/time.sleep(0.1)import sys,time
for i in range(20):sys.stdout.write("#")#stdout...标准输出(屏幕)....stdoin"标准输入"sys.stdout.flush()#强制刷新time.sleep(0.1)
7.文件“截断”:
f.truncate()#全部截断
f = open("yester2.py",'a',encoding="utf-8")
f.seek(5)
f.truncate(5)#字符"10"开始截断.... >>> 移动不好使....都是从头开始截取
8.二进制文件 “读” 和 “写”:
#f = open("yester.py",'rb')#二进制文件.....
f = open("yester2",'wb')#二进制文件.....
f.write("hello world".encode(encoding = 'utf-8'))
conclude:
“r”、“w”、“a”… readline/readlines…for line in f:…tell/seek/flush/truncate…
9.文件的修改:
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-#硬盘数据不会"往后挤
#文件修改#同时打开两个文件....边读边写
f = open("yester2.py",'r',encoding = "utf-8")
f_new = open("yester2.back.py",'w',encoding = "utf-8")for line in f:''' if "2.自己写第三方模块" in line:line = line.replace("2.自己写第三方模块","等我去享受")f_new.write(line)else:f_new.write(line)'''if "自己写第三方模块" in line:line = line.replace("自己写第三方模块","等我去享受")#字符串操作f_new.write(line)
f.close()
f_new.close()#with"语句".....with语句自动实现关闭文件的操作....
with open("yester2.py",'r',encoding = "utf-8")as f:for line in f:print(line)#在整个with语句下...执行完毕之后...自动关闭文件
with open("yseter2.py",'r',encoding = "utf-8") as f,\open("yester.back.py",'r',encoding = "utf-8") as f2:
#可以多打开几个...with.....as object
result:
1.文件数据不会往后挤…即不会在原文件…修改字符串(其他的数据)
2.
line.replace("str1","str2")#替换想修改项
with open('yester',‘r’,encode = “utf-8”) as f ,\ open('yester2','w',encode = 'utf-8') as f_new:
result:
line.replace… with open() as f ,\ open () as f_new:
三、字符编码转换详解:
(1)背景:
1.GB2313(7k+汉字) > GBK(2w) > GB18030(2w7)
2.发展到unicode…中文英文都占两个字节…(其他国家肯定不愿意啊…)
3.“utf-8”(unicode的扩展级)…可伸长的字符编码…
utf-8…英文编码依旧以ascll码的形式编码…中文3个字节
! ! ! 问题出现:1.不同的编译软件 2.乱码
deal:unicode 是统一的
#把中文的gbk编码用unicode编码显示一下,就出来了
#任何语言编码转成 Unicode 都能互相转换
!!!imporant:
1.python的字符编码默认的是"unicode"
2.python 解释器(文本编辑器) ,也可以认为是文件编码默认的是UTF-8;
3.开头声明:是为了告诉你当前解释器(python2.x / python3.x),用什么样的编码方式 去“解码”…
#Author:Jony c
#!/usr/bin/env python
# -*-coding:utf-8 -*-
import sys
print(sys.getdefaultencoding())
s = "你好啊"
print(s.encode('utf-8'))
print(s.encode('GBK'))
四、函数与函数式编程:
1. 先了解一下不同的编程方式:
有三种不同编程方式:面向对象、面向过程 和 函数式编程…(把它们想象成不同的武林门派):
面向对象 >>> 华山派 >>> “类” >>> class
面向过程 >>> 少林派 >>> “过程” >>> def
函数式编程 >>> 逍遥派 >>> “函数” >>> def
面向过程 和 函数式编程 都用 "def"定义,有什么区别:
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#面向对象:华山派-->>>>"类"——>>>class
#面向过程:少林派——>>>>过程——>>>>def
#函数式编程:逍遥派——>>>>函数——>>>>def#函数逻辑化和结构化的过程
#function_1:def fun_1():'''函数'''print("in the function")return 0def fun_2():'''过程'''print("in the function")print(fun_1(),fun_2())#过程不返回值
result:一个返回值/一个不返回值…
in the function
in the function
0 None
2.函数式编程的好处:
1.代码的多次利用 2.保持一致性 3.可扩展性
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import timedef easy():time_format = '%Y-%m-%d %X'time_current = time.strftime(time_format)with open("back.file",'a+',encoding = "utf-8" ) as f:f.write("---------123-------%s\n"%time_current)def test_1():print("in the test_1(导入优化)")easy()def test_2():print("in the test_2")easy()
def test_3():print("in the test_3")easy()test_1()
test_2()
test_3()
3.:函数式的return返回值:
(1):return即"结束":
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-def function():print("我是第一行")return 0print("我是第二行")
print(function())
result:
我是第一行
0
(2):return 可以返回那些值:
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def test_1():pass#占位符
def test_2():print("in the test2")return 0 #object....对象输出
def test_3():print("in the test2")return 0,"adasd",[1.,2.5,3],{"a_test":"123"}#tuple元组输出
print(test_1(),test_2(),test_3())
result:
in the test2
in the test2
None 0 (0, ‘adasd’, [1.0, 2.5, 3], {‘a_test’: ‘123’})
返回数目 = 0;返回0
返回数目 = 1 ;返回object
返回数目 >1 ;返回元组 (…)
(3):为什么要有这个…“返回值”
因为整个编程,会根据这个return值,进行判断后面的程序要在怎么来进行…(continue 还是 over…)
返回值:1.return 后面的执行吗?
2.return 返回什么?
3.为什么 return ?
4.函数的参数详解:
(1)形参与实参,"位置"参数 和 "关键字"参数…
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-def test(x,y):#这里是形式参数...print(x)print(y)
test(1,2)#1,2是具体的实际参数..位置参数.....与形参一一匹配
test(x=1,y=2)#关键参数....
#test(x=1,2)>>>>>>会报错.....关键参数不能写在位置参数前面
test(1,y = 2)
result:
1.形参/实参
2.传输形式上分为:位置参数/关键字参数…(关键字参数 不能放在 位置参数前 )
(2)默认参数:
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def test_1(x=1,y=9):print(x,y)
test_1(10)def test_2(x=1,y=9):print(x,y)
test_2()
默认参数特点:调用函数的时候,默认参数非必须传递
(3)参数组:(参数组要往后放…)
def test_1(*args):#以N个"位置参数"....传给形参>>>形成tuple元组参数print(args)
#test_1(导入优化)(1,2,3,4,5,6)
test_1(*[1,2,3,4,5,6])
#上面两种形式传回给形参
def test_2(**kwargs):#以N个"关键字参数"传回给形参.....转换成字典形式print(kwargs)print(kwargs['name'])print(kwargs['age'])print(kwargs['weight'])print(kwargs['hobbit'])
#test_2(name = "alex",age =18,hobbit = "tsla",weight = 100)
test_2(**{"name" :"alex","age":18,"hobbit" : "tsla","weight" : 100})
result:
*arges >>> "位置"参数 / *[…] 的 形式去传… >>> 元组的形式
**arge >>> "关键字"参数 / **{…} 的形式去传 … >>> 字典的形式
5.局部变量/全局变量:
(1)作用域不同:
#子程序中定义的变量为局部变量,程序一开始定义的变量是全局变量
# 全局变量的作用域使整个程序,局部变量作用域是定义该变量的子程序
# 局部变量和全局变量重名时:
# 定义局部变量的子程序内,局部变量起作用;在其他地方全局变量其作用
name = "jony"
def name_change(name):# name = "alex"print(name)#局部作用域
name_change("old boy")
print(name)
result:
old boy
jony
(2)默认参数:
name_1 = "jony"
def name_change():global name_1name_1 = "alex"print(name_1)#局部作用域
name_change()
print(name_1)
result:
alex
alex
这样把一个 局部变量 变为 全局变量…global…
但是:字典/列表/集合(数据很多)…可以在局部里面改,元组,字符串…改不了…
(3)局部变量 可以去改 全局变量…? 回答:是的…下面举例…
__author__ = "Alex Li"school = "Oldboy edu."
names = ["Alex","Jack","Rain"]#字符串改不了....数组/字典/集合(数据很多)可以改...
names_tuple = (1,2,3,4)#元组改不了
def change_name():names[0] = "金角大王"print("inside func",names)change_name()
print(names)
result:
inside func [‘金角大王’, ‘Jack’, ‘Rain’]
[‘金角大王’, ‘Jack’, ‘Rain’]
6.递归:就是 自己调"自己":
满足3个条件:
1.有一定的终止"条件"
2.递归模式逐渐减小
3.递归效率不高,递归模式增大,会导致 “栈溢出”…(递归999次)
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-#递归(函数自己调用自己)自己给你终结程序"999"
'''def calc(n):print(n)return calc(n+1)
calc(0)'''
#递归:1.必须有一个终止条件2.每一次递归,规模比上一次有所减少
# 3.递归效率不高,递归层次过高会导致栈溢出
def cala(n):print(n)if int(n/2)>0:return cala(int(n/2))print(">>>>",n)
cala(10)
7. 高阶函数:一个函数的形参接收另一个函数…
#Author:Jony c
#!/usr/bin/env python
# -*- coding:utf-8 -*-#一个函数接收并一个函数作为参数
def add(x,y,f):return f(x)+f(y)
res = add(-6,-9,abs)
print(res)