1.列表实例:由字符串创建一个作业评分列表,做增删改查询统计遍历操作。例如,查询第一个3分的下标,统计1分的同学有多少个,3分的同学有多少个等。
>>> ls=list('123456789') >>> ls ['1', '2', '3', '4', '5', '6', '7', '8', '9'] >>> ls.append ('10') >>> ls ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] >>> ls.pop(0) '1' >>> ls ['2', '3', '4', '5', '6', '7', '8', '9', '10'] >>> ls.index ('3') 1 >>> ls.count ('1') 0 >>> ls.count ('3') 1 >>>
2.字典实例:建立学生学号成绩字典,做增删改查遍历操作。
>>> ls={'文哥':'65','文爷':'64','文仔':'62'}
>>> ls
{'文哥': '65', '文爷': '64', '文仔': '62'}
>>> ls['文兄']='90'
>>> ls
{'文哥': '65', '文爷': '64', '文仔': '62', '文兄': '90'}
>>> ls.keys
<built-in method keys of dict object at 0x0000000002F081F8>
>>> ls.keys ()
dict_keys(['文哥', '文爷', '文仔', '文兄'])
>>> ls.values ()
dict_values(['65', '64', '62', '90'])
>>> ls.items ()
dict_items([('文哥', '65'), ('文爷', '64'), ('文仔', '62'), ('文兄', '90')])
>>> ls.get ('文兄')
'90'
>>> ls.pop('文兄')
'90'
>>> ls
{'文哥': '65', '文爷': '64', '文仔': '62'}
3.列表,元组,字典,集合的遍历。总结列表,元组,字典,集合的联系与区别。
>>> ls1=list('12345621354') >>> ls1 ['1', '2', '3', '4', '5', '6', '2', '1', '3', '5', '4'] >>> ls2=tuple('1197580969') >>> ls2 ('1', '1', '9', '7', '5', '8', '0', '9', '6', '9') >>> ls3={'a':'1','b':'2','c':'3'} >>> ls3 {'a': '1', 'b': '2', 'c': '3'} >>> ls4=set('1235431843') >>> ls4 {'4', '2', '1', '5', '8', '3'} >>> for i in ls1: print(i,end=' ') 1 2 3 4 5 6 2 1 3 5 4 >>> for i in ls2: print(i,end=' ') 1 1 9 7 5 8 0 9 6 9 >>> for i in ls3: print(i,ls3[i],end=' ') a 1 b 2 c 3 >>> for i in ls4: print(i,end=' ') 4 2 1 5 8 3 >>>
列表使用【】,元组使用(),字典使用{},集合使用[()];
列表、字典、集合能增加、修改、删除,而元组不能;
元组创建较简单,只需要在括号中添加元素并使用逗号隔开,列表则相对复杂多。
4.英文词频统计实例
待分析字符串
分解提取单词
大小写 txt.lower()
分隔符'.,:;?!-_’
计数字典
排序list.sort()
输出TOP(10)
z=''' Only you can make all this world seem right Only you can make the darkness bright Only you and you alone can thrill me like you do And fill my heart with love for only you Only you can make this change in me For it's true you are my destiny When you hold my hand I understand the magic that you do You're my dream come true My one and only you Only you can make all this world seem right Only you can make the darkness bright Only you and you alone can thrill me like you do And fill my heart with love for only you Only you can make this change in me For it's true you are my destiny When you hold my hand I understand the magic that you do You're my dream come true My one and only you ''' for i in ",.": z=z.replace(i,",") for i in z: z=z.lower() words=z.split(" ") keys=set(words) dict={} for i in keys: dict[i] = words.count(i) ls = list(dict.items()) ls.sort(key = lambda x:x[1],reverse=True) for i in range(10): print(ls[i])