- 字典实例:建立学生学号成绩字典,做增删改查遍历操作。
代码如下:
d={'a':90,'b':98,'c':97}
print(d.get('a'))
d.pop('c')
print(d)
d['e']=95
print(d)
d['a']=91
print(d)
for i in d:
print(i,d[i])
运行结果:
2.列表,元组,字典,集合的遍历,总结列表,元组,字典,集合的联系与区别。
代码如下:
ls=list('2345679900') tu=tuple('2354687879') print(ls) print(tu) dc=dict(zip(ls,tu)) print(dc) print('ls遍历 ') for i in ls: print(i) print('tu遍历 ') for i in tu: print(i) print('dict遍历 ') for i in dc: print(i,dc[i])
运行结果:
区别:
列表和元组是有序的,字典和集合是无序的,列表是可变的数据类型,即这种类型是可以被改变的,并且列表是可以嵌套的,列表通过中括号中用逗号分隔的项目定义。元组是不可变的。即你不能修改元组。元组通过圆括号中用逗号分隔的项目定义。元组通常用在使语句或用户定义的函数能够安全的采用一组值的时候,即被使用的元组的值不会改变。元组可以嵌套。字典通过大括号中用键值对和逗号分隔的项目定义,用空间换取时间。集合只有键没有值,可以把元组或序列中不重复的找出来,并可以做交集并集等操作。
3.英文词频统计实例
- 待分析字符串
- 分解提取单词
- 大小写 txt.lower()
- 分隔符'.,:;?!-_’
- 单词列表
- 单词计数字典
代码如下:
day='''Well I wonder could it be When I was dreaming about you baby You were dreaming of me Call me crazy Call me blind To still be suffering is stupid after all of this time Did I lose my love to someone better And does she love you like I do I do, you know I really really do Well hey So much I need to say Been lonely since the day The day you went away So sad but true For me there's only you Been crying since the day I remember date and time September twenty second Sunday twenty five after nine In the doorway with your case No longer shouting at each other There were tears on our faces And we were letting go of something special Something we'll never have again I know, I guess I really really know Why do we never know what we've got till it's gone How could I carry on Cause I've been missing you so much I have to say''' day=day.lower() for i in ',."?': day=day.replace(i,' ') words=day.split(' ') print(words)
dict={}
for i in words:
dict[i]=words.count(i)
print(dict)
运行结果: