Python--04--数据容器(总结)

Python--04--数据容器(总结)
提示文章写完后目录可以自动生成如何生成可参考右边的帮助文档文章目录1.数据容器_通用操作2.数据容器_小练习练习一水果清单练习二学生成绩表练习三评论内容3.数据容器_总结1.数据容器_通用操作# 以下这五个函数既能定义对应的【空容器】又能将【其他类型】转换为对应的数据类型# 1.list 函数1.定义空列表。2.将【可迭代对象】转换为列表res1list(range(8))res2list(欢迎来到尚硅谷)res3list({10,20,30,40,50})res4list({张三:75,李四:60,王五:85}.items())print(type(res1),res1)print(type(res2),res2)print(type(res3),res3)print(type(res4),res4)# 2.tuple 函数1.定义空元组。2.将【可迭代对象】转换为元组res1tuple(range(8))res2tuple(欢迎来到尚硅谷)res3tuple({10,20,30,40,50})res4tuple({张三:75,李四:60,王五:85})print(type(res1),res1)print(type(res2),res2)print(type(res3),res3)print(type(res4),res4)# 3.set 函数1.定义空集合。2.将【可迭代对象】转换为集合res1set(range(8))res2set(欢迎来到尚硅谷)res3set({10,20,30,40,50})res4set({张三:75,李四:60,王五:85})print(type(res1),res1)print(type(res2),res2)print(type(res3),res3)print(type(res4),res4)# 4.str 函数1.定义空字符串。2.将【任意类型】转换为字符串res1str(range(8))res2str(欢迎来到尚硅谷)res3str({10,20,30,40,50})res4str({张三:75,李四:60,王五:85})res5str(False)res6str(None)res7str(100)print(type(res1),res1)print(type(res2),res2)print(type(res3),res3)print(type(res4),res4)print(type(res5),res5)print(type(res6),res6)print(type(res6),res6)print(type(res7),res7)# 5.dict 函数1.定义空字典。2.将【可迭代对象】转换为字典# 备注交给dict函数的内容必须是键值对才可以否则就会报错res1dict({张三:75,李四:60,王五:85})res2dict([(张三,75),(李四,60),(王五,85)])res3dict(((张三,75),(李四,60),(王五,85)))res4dict({(张三,75),(李四,60),(王五,85)})print(type(res1),res1)print(type(res2),res2)print(type(res3),res3)print(type(res4),res4)# 所有的数据容器都支持【成员运算符】 in / not in 作用判断某个“元素”是否在于容器中。hobby[抽烟,喝酒,烫头]nums(10,20,30,40,50)messagehello,atgiugucitys{北京,天津,上海,重庆}score{张三:75,李四:60,王五:85}print(喝酒notinhobby)print(20notinnums)print(helnotinmessage)print(上海notincitys)print(李华notinscore)2.数据容器_小练习练习一水果清单# 练习一水果清单fruits{苹果:4.5,香蕉:3.2,橙子:5.8,草莓:12.0,哈密瓜:8.8}# 需求1打印所有的水果forkeyinfruits:print(f{key}{fruits[key]}元/斤)# 需求2找到最贵水果keymax(fruits,keyfruits.get)print(f最贵的水果是{key}价格是{fruits[key]}元/斤)练习二学生成绩表# 练习二学生成绩表students[{name:张三,scores:{语文:88,数学:92,英语:95}},{name:李四,scores:{语文:75,数学:83,英语:80}},{name:王五,scores:{语文:92,数学:95,英语:88}}]# 需求1计算每位学生的平均分forstuinstudents:# 获取当前学生的成绩列表score_liststu[scores].values()# 计算平均值avgsum(score_list)/len(score_list)print(f{stu[name]}的平均成绩是{avg:.1f})# 需求2找到总分最高的学生deffind_best():# 记录分数最高的学生best_students[]# 记录最高分best_score0# 循环遍历forstuinstudents:# 获取当前学生的总成绩totalsum(stu[scores].values())# 当前学生的成绩如果大于best_score就会更新数据iftotalbest_score:best_students[stu[name]]best_scoretotal# 当前学生的成绩与最高分相同就加入列表eliftotalbest_score:best_students.append(stu[name])print(f最高分为{best_score}取得最高分的学生有{best_students})find_best()练习三评论内容comment这家奶茶真好喝环境也不错就是价格有点贵好喝好喝好喝强烈推荐# 需求1统计“好喝”出现次数print(comment.count(好喝))# 需求2将字符串中的“贵”替换为“略高”comment2comment.replace(贵,略高)print(comment2)# 需求3是否包含“推荐”两个字print(推荐incomment)3.数据容器_总结