1.字典
字典是一种key-value的数据类型
特性:
字典是无序的
info = {
‘stu01‘:"Lily",
‘stu02‘:"Xiaoxiao",
‘stu03‘:"Zizhou",
}
print(info)
(1)查找
info[‘stu02‘] #如果字典里没有会报错
info.get(‘stu02‘)
#判断字典里是否有stu03
print(‘stu03‘ in info)
(2)修改
info["stu01"] = "LILY"
(3)添加
info["stu04"] = "Xishi"
(4)删除
del info["stu01"]
info.pop("stu01")
info.popitem() #随机删除
info = {
‘stu01‘:"Lily",
‘stu02‘:"Xiaoxiao",
‘stu03‘:"Zizhou",
}
xs = {
‘stu01‘:"Zhangzi",
‘student1‘:"Xiannv",
‘student2‘:"Wangzi",
}
#合并两个字典,有交叉的更新,没有的添加
info.update(xs)
#把字典转成列表
print(info.items())
dict.fromkeys([1,2,3]) #初始化一个新的字典,列表中的值是字典的key
字典的循环:
for i in info:
print(i,info[i])
for k,v info.items()
print(k,v) #将字典转成列表,然后循环
字典的多级嵌套:
data = {
"陕西":{
"西安":{
"蓝田":{"蓝田玉"}
"户县":{"户太八号"}
"宝鸡":{
"岐山":{"擀面皮"}
"凤翔":{}
}
"广西":{
"桂林":{
"阳朔":{"十里画廊"}
"灵川":{}
"南宁":{
"上林":{}
"宾阳":{}
}
}
data["陕西"]["西安‘‘][1] += ",汤峪温泉"
print(data["陕西"]["西安‘‘])
输出:
["蓝田玉","汤峪温泉"]
2.集合
list_1 = [1,4,5,7,3,6,7,9]
#集合1
list_1 = set(list_1)
#集合2
list_2 = set([2,6,0,66,22,8,4])
print(list_1,list_2)
(1)交集
print(list_1.intersection(list_2))
或
print(list_1 & list_2)
(2)并集
print(list_1.union(list_2))
或
print(list_1 | list_2)
(3)差集
print(list_1.difference(list_2))
print(list_2.difference(list_1))
或
print(list_1 - list_2)
(4)子集
print(list_1.issubset(list_2)) #判断list_1是否是list_2的子集
print(list_2.issuperset(list_1)) #判断list_1是否是list_2的子集
(5)对称差集
print(list_1.symmetric_difference(list_2))
或
print(list_1 ^ list_2)
#添加
list_1.add(999)
list_1.update([123,456,789]) #添加多项
#删除
print(list_1.pop())
print(list_1.remove(111)) #不存在会报错
print(list_1.discard(123))
3.文件读写
#打开文件
data = open("file_name",encoding = "utf-8").read() #只能打开文件,不能对文件操作
print(data)
f = open("file_name",encoding = "utf-8") #文件句柄
data = f.read()
print(data)
f = open("file_name",‘w‘,encoding = "utf-8") #以写模式打开一个新文件
f.write("我的家在东北松花江上")
f = open("file_name",‘a‘,encoding = "utf-8") #a=append追加
f.write("我的家在东北松花江上,啊。。。")
f.close() #关闭文件
#循环
for line in f.readlines():
print(line.strip())
#不打印第十行
方法1:
for index,line in enumerate(f.readline()):
if index == 9:
print("---------------------------------")
continue
print(line.strip())
方法2:
count = 0
for line in f:
if count == 9:
print("----------------------------------")
count += 1
continue
print(line)
count +=1
f = open("file_name",‘a‘,encoding = "utf-8")
print(f.readline()) #读一行
for i in range(5):
print(f.readline()) #读前5行
f = open("file_name",‘r‘,encoding = "utf-8")
print(f.tell()) #打印光标当前的位置
print(f.readline())
print(f.tell()) #以字符记数
f.seek(0) #回到0位置
#打印字符集
print(f.encoding)
#强制刷新
f = open("file_name",‘w‘,encoding ="utf-8")
f.write("helloworld")
f.flush() #默认缓存满了刷新到硬盘,此操作强制刷新到硬盘
例子:打印一串#
import sys,time
for i in range(20)
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.1)
f = open("file_name",‘a‘,encoding = "utf-8")
f.truncate(20) #截断,从头开始截
f.truncate() #清空
f = open("file_name",‘r+‘,encoding = "utf-8") #读写,在文件最后追加
f = open("file_name",‘w+‘,encoding = "utf-8") #写读,建一个新文件,然后写
f = open("file_name",‘a+‘,encoding = "utf-8") #追加写读
f = open("file_name",‘rb‘) #以二进制模式读文件
f = open("file_name",‘wb‘) #以二进制模式写文件
f.write("helloword\n".encode())
4.文件修改
#同时打开两个文件,从file_name1里读,往file_name2里写
f = open("file_name1",‘r‘,encoding = "utf-8")
f_new = open("file_name1",‘w‘,encoding = "utf-8")
for line in f:
if "I am Leilu" in line:
line = line.replace("I am Leilu","I am Xiaoxiao")
f_new.write(line)
f.close()
f_new.close()
程序练习:
实现简单的shell sed替换功能
f = open("file_name1",‘r‘,encoding = "utf-8")
f_new = open("file_name1",‘w‘,encoding = "utf-8")
find_ str = sys.argv[1]
replace_str = sys.argv[2]
for line in f:
if find_str in line:
line = line.replace(find_str,replace_str)
f_new.write(line)
f.close()
f_new.close()
五、with语句
# f = open("file_name1",‘r‘,encoding = "utf-8")
#为了避免打开文件后忘记关闭,可以通过管理上下文
#当with代码块执行完毕时,内部会自动关闭并释放文件资源
with open("file_name1",‘r‘,encoding = "utf-8") as f:
for line in f:
print(line)
#同时打开多个文件
with open("file_name1",‘r‘,encoding = "utf-8") as f
open("file_name2",‘r‘,encoding = "utf-8") as f2:
for line in f:
print(line)
六、字符编码与转码
1.在python2默认编码是ASCII, python3里默认是unicode
2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间
3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string
GBK转换为UTF-8格式流程:首先通过解码decode转换为Unicode编码
然后通过编码encode转换为UTF-8编码
UTF-8转换为GBK格式流程:首先通过解码decode转换为Unicode编码
然后通过编码encode转换为GBK编码
import sys
print(sys.getdedaultencoding()) #打印默认字符编码
s = "你好"
s_to_unicode = s.decode("utf-8") #UTF-8解码转换为Unicode
s_to_gbk = s_to_unicode.encode("gbk") #Unicode编码转换为GBK
gbk_to_utf8 = s_to_gbk.decode("gbk").encode("utf-8") #GBK转换为UTF-8
七、函数和函数式编程
1.面向对象:类---> class
2.面向过程:过程--->def
3.函数式编程:函数--->def
编程语言中的函数定义:函数是逻辑结构化和过程化的一种编程方法
python中函数定义方法:
def test(x):
"""The function definitions"""
x+=1
return x
def:定义函数的关键字
test:函数名
( ):定义形参
""" """:文档描述(非必要)
#函数
def func1()
"""testing1"""
print(‘in the func1‘)
return 0
#过程
def func2()
"""testing2"""
print(‘in the func2‘)
调用:
x=func1()
y=func2()
print(x)
print(y)
python中函数和过程没有明显的界限,过程默认返回None
def logger()
with open(‘a.text‘,‘a+‘) as f:
f.write(‘end action\n‘)
logger()
优点:
1.代码重用
2.保持一致性
3.可扩展性
函数返回值:
返回值数=0:返回None
返回值数=1:返回object(对象)即写什么返回什么
返回值数>1:返回tuple(元组)
(1)位置参数调用:形参和实参要一一对应
def test(x,y): #x,y形参,不是真正存在的参数,不占内存空间
print(x)
print(y)
test(1,2) #1,2实参,内存中真正存在的参数,占内存空间
(2)关键字调用:实参与形参顺序无关
def test(x,y):
print(x)
print(y)
test(y=2,x=1)
注:关键参数不能写在位置参数前面
(3)默认参数:
def test(x,y=2):
print(x)
print(y)
test(1)
test(1,3)
test(1,y=3)
特点:调用函数的时候,默认参数非必须传递
(4)参数组:实参数目不固定
# *args:接收位置参数,转换成元组的方式
def test1(*args):
print(args)
test(1,2,3,4,5) #多个参数传给args,放在元组里
test(*[1,2,3,4,5])
# **kwargs:把N个关键字参数,转换成字典的方式
def test2(**kwargs):
print(kwargs)
print(kwargs[‘name‘])
print(kwargs[‘age‘])
print(kwargs[‘sex‘])
test2(name=‘leilu‘,age=24,sex=‘F‘)
test2(**{‘name‘:‘leilu‘,‘age‘:24,‘sex‘:‘F‘})
与位置参数结合:
def test3(name,**kwargs):
print(name)
print(kwargs)
test3(‘leilu‘,age=24,sex=‘F‘)
def test4(name,age=24,**kwargs):
print(name)
print(age)
print(kwargs)
test4(‘leilu‘,sex=‘F‘)
test4(‘leilu‘,18,sex=‘F‘)
test4(‘leilu‘,age=18,sex=‘F‘)
def test4(name,age=24,*args,**kwargs):
print(name)
print(age)
print(args)
print(kwargs)
test4(‘leilu‘,sex=‘F‘)
test4(‘leilu‘,age=18,sex=‘F‘,hobby=‘eat‘)
test4(‘leilu‘,1,sex=‘F‘, hobby=‘eat‘)
函数式编程介绍:
函数式编程就是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数我们称之为没有副作用。
特点:允许把函数本身作为参数传入另一个函数,还允许返回一个函数
Python对函数式编程提供部分支持
八、局部变量和全局变量
1.局部变量
def change_name(name):
print("before change",name)
name = "LeiLu" #局部变量,这个函数就是这个函数的作用域
print("after change",name)
name = "leilu"
change_name(name)
print(name)
2.全局变量
age = 24 #全局变量
def chang_name(name):
global age #修改全局变量,声明(不要用)
age = 18
print("before change",name)
name = "LeiLu"
print("after change",name)
name = "leilu"
change_name(name)
print(name)
print("age:",age)
#列表、字典、集合、类都是可以在函数中修改的
#字符串、整数是不能在函数中修改的
names = ["leilu","xiaoxiao"]
name_tuple = (1,2,3,4)
def change_name():
name[0] = "Xixi"
print(names)
print(names)
九、递归
特性:
1.必须有一个明确的结束条件
2.每次进入更深一层递归时,问题规模相比上次递归都应有所减少
3.递归效率不高
def calculate(n):
print(n)
if n/2 > 0:
return calculate(int(n/2))
print("-->",n)
calculate(10)
十、高阶函数
变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数
def add(x,y,f)
return f(x)+f(y)
res = add(3,-6,abs)
print(res)