1、字典实例:建立学生学号成绩字典,做增删改查遍历操作。
d={'1':'100','2':'72','3':'98','4':'88'} print(d.get('3')) d.pop('1') print(d.items()) d['3']=120 print(d.items()) for i in d: print(i)
结果:
98
dict_items([('2', '72'), ('3', '98'), ('4', '88')])
dict_items([('2', '72'), ('3', 120), ('4', '88')])
2
3
4
2、列表,元组,字典,集合的遍历。
list=['1','2','3','4','5','6'] tu=('01','02','03','04','05','06') dic={'01':'88','02':'99','03':'77','04':'86','05':'96'} jihe=set(list) for i in list: print(i) for i in tu: print(i) for i in dic: print(i,dic[i]) for i in jihe: print(i)
结果:
1
2
3
4
5
6
01
02
03
04
05
06
01 88
02 99
03 77
04 86
05 96
5
1
6
3
2
4
3、
3、总结列表,元组,字典,集合的联系与区别。
元组和列表在结构上没有什么区别,唯一的差异在于元组是只读的,不能修改。集合就是我们数学学的集合,没有什么特殊的定义。集合最好的应用是去重。集合没有特殊的表示方法,而是通过一个set函数转换成集合。最后一个是字典,字典存储键值对数据,字典最外面用大括号,每一组用冒号连起来,然后各组用逗号隔开,字典最大的价值是查询,通过键,查找值。
4、
3.英文词频统计实例
A.待分析字符串
B.分解提取单词
a.大小写 txt.lower()
b.分隔符'.,:;?!-_’
c.单词列表
C.单词计数字典
news='''All the times that you rain on my parade And all the clubs you get in using my name You think you broke my heart Ohhh girl for goodness sake You think I'm crying Oh my ohhh, well I ain't! And I didn't wanna write a song 'Cause I didn't want anyone thinking I still care, I don't But, you still hit my phone up And baby I be moving on And I think you should be somethin' I don't wanna hold back Maybe you should know that My mama don't like you and she like's everyone''' news=news.lower() for i in ',!': news=news.replace(i,' ') words=news.split(' ') print(words) dict={} for i in words: dict[i]=words.count(i) print(dict)
结果:
['all', 'the', 'times', 'that', 'you', 'rain', 'on', 'my', 'parade
and', 'all', 'the', 'clubs', 'you', 'get', 'in', 'using', 'my', 'name
you', 'think', 'you', 'broke', 'my', 'heart
ohhh', 'girl', 'for', 'goodness', 'sake
you', 'think', "i'm", 'crying
oh', 'my', 'ohhh', '', 'well', 'i', "ain't", '
and', 'i', "didn't", 'wanna', 'write', 'a', "song
'cause", 'i', "didn't", 'want', 'anyone', 'thinking', 'i', 'still', 'care', '', 'i', "don't
but", '', 'you', 'still', 'hit', 'my', 'phone', 'up
and', 'baby', 'i', 'be', 'moving', 'on
and', 'i', 'think', 'you', 'should', 'be', "somethin'", 'i', "don't", 'wanna', 'hold', 'back
maybe', 'you', 'should', 'know', 'that
my', 'mama', "don't", 'like', 'you', 'and', 'she', "like's", 'everyone']
{'all': 2, 'the': 2, 'times': 1, 'that': 1, 'you': 7, 'rain': 1, 'on': 1, 'my': 5, 'parade
and': 1, 'clubs': 1, 'get': 1, 'in': 1, 'using': 1, 'name
you': 1, 'think': 3, 'broke': 1, 'heart
ohhh': 1, 'girl': 1, 'for': 1, 'goodness': 1, 'sake
you': 1, "i'm": 1, 'crying
oh': 1, 'ohhh': 1, '': 3, 'well': 1, 'i': 8, "ain't": 1, '
and': 1, "didn't": 2, 'wanna': 2, 'write': 1, 'a': 1, "song
'cause": 1, 'want': 1, 'anyone': 1, 'thinking': 1, 'still': 2, 'care': 1, "don't
but": 1, 'hit': 1, 'phone': 1, 'up
and': 1, 'baby': 1, 'be': 2, 'moving': 1, 'on
and': 1, 'should': 2, "somethin'": 1, "don't": 2, 'hold': 1, 'back
maybe': 1, 'know': 1, 'that
my': 1, 'mama': 1, 'like': 1, 'and': 1, 'she': 1, "like's": 1, 'everyone': 1}
>>>