python学习四(基础知识)
python基础学习四
本章内容
- 列表
- 元组
- 字符串
- 字典
- 文件操作
- 作业实例
1.列表
列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作
定义列表
names = ['wuchao','jinxin','xiaohu','sanpang','ligang'] #查 切片 默认第一个从0开始查找 print("列表查询:") print(names[1:])#取到最后 print(names[1:-1])#取到倒数第二个值 print(names[1:-1:1])#从左到右一个一个取 print(names[1::2])#从左到右隔一个去取 print(names[3::-1]) #添加 append insert print("列表添加:") names.append("hzw") #默认插到最后一个位置 print(names) names.insert(1,"hzw") #将数据插入到任意一个位置 print(names) #修改 names[1]='wc' print(names) names[1:3]=['a','b'] print(names) #删除 remove pop del names.remove(names[0])#删除指定元素 print(names)
a= names.pop()#删除最后一个值
b=names.pop(1)#删除后,返回删除的值 print(names) print(b) del names[1] #即可删除整个列表也可以删除某个值 print(names) del names print(names)
names.remove(['wuchao','jinxin']) print(names) #count:计算某元素出现次数 t=['to', 'be', 'or', 'not', 'to', 'be'].count('to') print(t) #extend 扩展 a = [1, 2, 3] b = [4, 5, 6] a.extend(b) print(a) print(b) # index # 根据内容找位置 a = ['wuchao', 'jinxin', 'xiaohu', 'ligang', 'sanpang', 'ligang', ['wuchao', 'jinxin']] first_lg_index = a.index("ligang") print("first_lg_index",first_lg_index) little_list = a[first_lg_index+1:] second_lg_index = little_list.index("ligang") print("second_lg_index",second_lg_index) second_lg_index_in_big_list = first_lg_index + second_lg_index +1 print("second_lg_index_in_big_list",second_lg_index_in_big_list) print("second lg:",a[second_lg_index_in_big_list]) #reverse a = ['wuchao', 'jinxin', 'xiaohu','ligang', 'sanpang', 'ligang'] a.reverse() print(a) x = [3,4,7,2,5] x.sort(reverse=True) print(x) y = [1,2,3,4] y.pop() print(y) y.pop() print(y)
2.元组
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
定义:
names = ("alex","jack","eric")
它只有2个方法,一个是count,一个是index
3.字符串
a = "Let's go" print(a) #重复输出字符串 print('hello'*2) #[],[:] 通过索引获取字符串中字符,这里和列表的切片操作是相同的 print('helloworld'[2:]) #in 成员运算符,如果字符串中包含给定的字符返回True print('el' in 'hello') #% 格式字符串 print('alex is a good teacher') print('%s is a good teacher' %'alex') # + 字符串拼接 a = "123" b = "456" c = "44" #c = a+b #print(c) e = ''.join([a,b,c]) print(e) f = '-------'.join([a,b,c]) print(f) #String的内置方法 st = 'he\tllo kitty' print(st.count('l')) #统计元素个数 print(st.capitalize()) #首字母大写 print(st.center(50,'-')) #居中 print(st.endswith("y")) #判断是否以某个内容结尾 print(st.startswith('he'))#判断是否以某个内容开头 print(st.expandtabs(tabsize=20)) st = 'hello kitty {name} is {age}' print(st.find('t')) #查找到第一个元素,并将索引值返回 print(st.format(name="alex",age=37)) print(st.format_map({'name':'alex','age':22})) print(st.index('t')) print("abc456".isalnum()) print("1223".isdecimal()) print('1122'.isdigit()) print("126.999".isdigit()) print('abc'.isidentifier()) print("abc".islower()) print("Abc".isupper()) print(" e".isspace()) print("My Title".istitle()) print("My title".lower()) print("My title".upper()) print("My title".swapcase()) print("My title".ljust(50,'*')) print("My title".rjust(50,'*')) print(" \tMy title\n".strip()) print(" \tMy title\n".lstrip()) print(" \tMy title\n".rstrip()) print('ok') print('My title title'.replace('itle','lesson',1)) print('My title title'.rfind('y')) print('My title title'.split(" ")) print('My title title'.split('i',1)) print('My title title'.title())
4.字典
字典一种key - value 的数据类型
字典的特性:
dict是无序的
key必须是唯一的
#增加 dic1 = {'name': 'alex'} dic1["age"] = 18 print(dic1) #键存在,不改动,返回字典中相应的键对应的值 ret=dic1.setdefault('age',19) print(dic1) print(ret) #键不存在,在字典中增加相应的键值对,并返回相应的值 dic1.setdefault('hobby','girl') print(dic1) #查 通过键查找 dic3 = {'name':'hzw','age':30,'hobby':'girl'} print(dic3['name']) print(dic3.keys()) print(type(dic3.keys())) print(list(dic3.keys())) print(list(dic3.values())) print(list(dic3.items())) #修改 dic3 = {'name':'hzw','age':30,'hobby':'girl'} dic3['age']=55 print(dic3) #dic4 = {'1':'h','2':'aa'} dic4 = {'1':'h', 'name':'aa'} dic3.update(dic4)# 键存在则更新,不存在则增加 print(dic3) print(dic4) #删除 #del 删除字典中指定键值对 dic5 = {'name':'hzw','age':30,'hobby':'girl'} del dic5['name'] print(dic5) #pop 删除字典中指定键值对,并返回该键值对的值 ret=dic5.pop("age") print(dic5) print(ret) #popitem随机删除某组键值对,并以元组方式返回值 dic5 = {'name':'hzw','age':30,'hobby':'girl'} a = dic5.popitem() print(a,dic5) #clear 清空字典 #dic5.clear() #print(dic5) #del dic5 #删除整个字典 #print(dic5) #其他操作以及涉及到的方法 dic6 = dict.fromkeys(['h1','h2','h3'],'test') print(dic6)#结果{'h1': 'test', 'h2': 'test', 'h3': 'test'} dic6['h3']='abc' print(dic6) dic7 = dict.fromkeys(['h1','h2','h3'],['test1','test2']) print(dic7)#结果{'h1': ['test1', 'test2'], 'h2': ['test1', 'test2'], 'h3': ['test1', 'test2']} dic7['h1'][1]='test3' print(dic7)#结果{'h1': ['test1', 'test3'], 'h2': ['test1', 'test3'], 'h3': ['test1', 'test3']} #字典嵌套 menu = { "广东省":{ "广州市":{ "天河区":{ "网易":{}, "广州塔":{}, }, "越秀区":{ "越秀公园":{}, "北京路":{}, "上下九路":{} } }, "揭阳市":{ "惠来县":{ "惠城":{}, "华湖":{}, }, }, }, "北京市":{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{}, }, }, '朝阳':{}, '东城':{}, }, "上海市":{}, "福建省": {}, }
5.文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
#打开文件,拿到句柄 f = open("小重山",'r',encoding='utf8') data = f.read() print(data) print() f.close() f = open("小重山", 'r', encoding='utf8') data1 = f.read(5) #取前5个字符 print(data1) print() f.close() f1 = open("小重山1", 'w', encoding='utf8') f1.write('hzw,hello world!!! \n') f1.write('访问愉快!!!') f1.close() num = 0 for i in f: #for内部将f对象做成一个迭代器,用一行取一行 num += 1 if num == 6: i = ''.join([i.strip(), 'hzw03']) print(i.strip())
6.作业实例
程序1:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
product_list = [ ('mac', 9000), ('kindle', 800), ('tesla', 900000), ('python book', 105), ('bike', 2000), ] #定义本金变量 saving = input('please input your money:') shopping_car = [] if saving.isdigit(): saving = int(saving) # for i in product_list: # print(product_list.index(i), i) while True: for i, v in enumerate(product_list, 1): print(i, ">>>", v) choice = input("选择购买商品编号[退出:q]:") if choice.isdigit(): choice = int(choice) if choice>0 and choice<len(product_list): p_item = product_list[choice-1]#按照索引值取的,所以需要减1 if p_item[1]<saving: saving-=p_item[1] shopping_car.append(p_item) else: print('余额不足,还剩%s'%saving) print(p_item) else: print('该商品编码不存在') elif choice == 'q': print("------------------您已经购买如下商品----------------------") for i in shopping_car: print(i) print('您还剩%s元钱' %saving) break else: print('invalid input')
程序2: 三级菜单
要求:
- 打印省、市、县三级菜单
- 可返回上一级
- 可随时退出程序
menu = { "广东省":{ "广州市":{ "天河区":{ "网易":{}, "广州塔":{}, }, "越秀区":{ "越秀公园":{}, "北京路":{}, "上下九路":{} } }, "揭阳市":{ "惠来县":{ "惠城":{}, "华湖":{}, }, }, }, "北京市":{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{}, }, }, '朝阳':{}, '东城':{}, }, "上海市":{}, "福建省": {}, } current_layer = menu #实现动态循环 parent_layers = [] #保存所有父级,最后一个元素永远都是父亲级 while True: for key in current_layer: print(key) choice = input(">>>:").strip() if len(choice) == 0:continue if choice in current_layer: #parent_layer = current_layer #上层赋值 parent_layers.append(current_layer) current_layer = current_layer[choice]#子层赋值 elif choice == "b": if parent_layers: current_layer = parent_layers.pop()#默认删除列表最后一个 else: print("无此项")

浙公网安备 33010602011771号