day3学python 字典+列表集合+文件读取

时间:2023-03-10 01:58:57
day3学python  字典+列表集合+文件读取

字典+列表集合+文件读取

字典示例

************************ 各地食品的三级菜单*************************

1.使用字典嵌套字典

2.采用死循环思路

3.对字典 循环打印 只可得第一级的key

4.for i in <范围>     //python的for循环实在与其他不同。  i 可为任意类型 不给参数限定 即会遍历范围

place={
"华北":{
"北京市":"北京烤鸭",
"天津市":"锅巴",
"河北省":"驴肉火烧",
},
"中南":{
"广东省":"早茶",
"河南省":"胡辣汤",
"湖北省":"热干面",
},
"华东":{
"上海市":"小笼包",
"江苏省":"锅盖面",
"浙江省":"西湖醋鱼"
},
"西南":{
"四川省":"担担面",
"云南省":"汽锅鸡",
"贵州省":"茅台酒"
}
}
while True:
for i in place:
print(i)
choice1=input("choose area or press B for back")
if choice1 in place:
while True:
for j in place[choice1]:
print('\t',j)
choice2=input("choose province or press B for back")
if choice2 in place[choice1]:
print('\t\t',place[choice1][choice2])
elif choice2=='B'or choice2=='b':
break
else:
print("put in wrong!")
while True:
choice3 = input("press B for back or Q for exit")
if choice3=='B'or choice3=='b':
break
elif choice3=='q'or choice3=='Q':
exit(0)
elif choice1 == 'B' or choice1 == 'b':
break
else:
print("put in wrong!")

======================================================================================
集合
#交集 A∩B
print(list_3.intersection(list_4))
print(list_3&list_4) #并集 A∪B
print(list_3.union(list_4))
print(list_3|list_4) #差集 A-B
print(list_3.difference(list_4))
print(list_3-list_4) #对称查缉A⊕B=A∪B-A∩B
print(list_3.symmetric_difference(list_4))
print(list_3^list_4) #A是否是B的子集
list_5=set([1,2,4])
print(list_5.issubset(list_3)) #增
list_3.add("x")
list_4.update([33,3,2])
print(list_3)
#删
list_3.remove(2) #只能删除集合中存在的东西 不存在会报错
list_3.discard(44) #不存在不会报错 #查 (列表 集合 字符串都用这种方法)
"x"in list_3
==============================================================================
文件
w只读是新创一个文件覆盖

# 文件句柄   
# open("打开文件目录",'w(只写)r(只读)a(add在后增加不能读)r+(读写-可读再追加)w+(写读)',encoding="utf-8")
f=open("actor",'r+',encoding="utf-8") # 不用最后close()文件
with open("actor",'r+',encoding="utf-8") as f:
#函数体 无需写f.close() #二进制文件的读rb 写wb
f=open("actor",'wb')
f.write("hello binary".encode("utf-8")) #读文件
f.read() #全部读出
f.readline() #按行读出 #低级读文件(将文件放于全内存中 只适用于小文件没用) for index,readline in enumerate(f.readlines()):
if index % 9==0:
print("=================")
print(readline) #高级读文件(效率最高 优先运用 有用) count=0
for line in f:
if count%9==0:
print("===========")
count+=1
continue
print(line)
count+=1 # read后 光标位置置于最后 再read时将无法读到东西
f.tell()  #输出光标位置 f.seek(0)   #改变光标位置到0 #truncate()文件清空
f.truncate(10)  #只读保留前10位的内容 其他清空 import sys,time
for i in range(20):      #flush()刷新内存区
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.3) #文件修改
f=open("actor",'r',encoding="utf-8")
f_new=open("actor_1",'w',encoding="utf-8") for line in f:
if "薛之谦" in line:
line=line.replace("薛之谦","cf")
f_new.write(line)
f.close()
f_new.close()