【作业】组合数据类型练习,英文词频统计实例
1、列表实例:由字符串创建一个作业评分列表,做增删改查询统计遍历操作。例如,查询第一个3分的下标,统计1分的同学有多少个,3分的同学有多少个等。
1 score = list('012332211') 2 print('分数为:',score) 3 print('1分的同学个数:',score.count('1')) 4 print('3分的同学个数:',score.count('3')) 5 print('第一个3分同学的下标为:',score.index('3')) 6 score.append('0') 7 print('添加一个0分在表的末尾:',score) 8 score.insert(0,'3') 9 print('添加一个3分在表的开头:',score) 10 score.pop(1) 11 print('删除第二个分数:',score)
2、字典实例:建立学生学号成绩字典,做增删改查遍历操作。
1 score = {'01':'100','02':'77','03':'88','04':'97','05':'97','05':'96','06':'60','07':'55','08':'90','09':'91','10':'59'} 2 print('成绩表:\n',score.items()) 3 score['11']='90' 4 print('添加学号为11的分数:\n',score.items()) 5 score['10']='99' 6 print('修改学号为10的分数为99分:\n',score.items()) 7 print('学号是:',score.keys()) 8 print('分数是:',score.values()) 9 found = input('输入学号查分数:') 10 print(score.get(found,"没有该学生的分数!"))
3、分别做列表,元组,字典,集合的遍历,并总结列表,元组,字典,集合的联系与区别。
1 ls = list('123456789') 2 ln = tuple('123456789') 3 s = {'01':'100','02':'99','03':'98','04':'97','05':'96','05':'96','06':'95','07':'98','08':'90','09':'91'} 4 a= set('123456789') 5 print('列表:',ls) 6 print('元组',ln) 7 print('字典',s) 8 print('集合',a) 9 print('\n列表的遍历:') 10 for i in ls: 11 print(i,' ',end=' ') 12 print('\n元组的遍历:') 13 for j in ln: 14 print(j,' ',end=' ') 15 print('\n字典的遍历:') 16 for k in s: 17 print(k,'',end=' ') 18 print('\n集合的遍历:') 19 for l in a: 20 print(l,'',end=' ')
属性 |
列表list |
元祖tuple |
字典dict |
集合set |
有序 |
是 (正向递增/反向递减) |
是 |
无 |
无 |
数据可重复 |
是 |
是 |
key值唯一 |
否 |
数据可修改 |
是 |
否 |
是 |
是 |
特点 |
查询速度随内容增加而变慢 占用内存较小 |
表达固定数据项、函数多返回值、 多变量同步赋值、循环遍历等情况下适用 |
改&查操作速度快,不会因key值增加而变慢。占用内存大,内存浪费多(利用空间成本换时间) |
数据独立性: 能够过滤重复参数 |
4、英文词频统计实例
思路:待分析字符→分解提取单词→大小写 txt.lower()→分隔符'.,:;?!-_’ →计数字典→排序list.sort()→输出TOP(10)。
1 write='''It was Mother’s Day.Sun Zheng thought he should do something for his mother. 2 He decided to help his mother do some housework.After school he went to a shop to buy some food on his way home. 3 When he got home,he did his best to cook some nice food,though he couldn’t do the cooking well. 4 Then he cleaned the room.He felt very tired,but he was very happy. 5 When his father and his mother came back and saw the clean rooms and dishes which weren’t so nice,they were very happy. 6 They had their supper together.His mother said,"Thank you,my child!"''' 7 8 exc={'the','to','and','on','a','was'} 9 write = write.lower() 10 for i in ''',.!?''': #去掉标点符号 11 write = write.replace(i,' ') 12 words = write.split(' ') #分词,单词的列表 13 keys = set(words) #出现过单词的集合,字典的Key 14 dic = {} 15 for w in exc: #排除无意义的单词 16 keys.remove(w) 17 for i in keys: 18 dic[i]=words.count(i) #单词出现次数的字典 19 diry = list(dic.items()) #把字典转换为列表 20 diry.sort(key = lambda x:x[1],reverse = True) #按出现的次数降序排序 21 for i in range(10): 22 print(diry[i])