- 字典实例:建立学生学号成绩字典,做增删改查遍历操作。
#创建一个空字典 dict={} s=dict print(s) #增加键值对(学号-成绩) s[‘001‘]=60 s[‘002‘]=70 s[‘003‘]=80 s[‘004‘]=90 print(s) #删除 s.pop(‘004‘) print(s) #修改 s[‘001‘]=69 print(s) #查找键是否存在 s.get(‘005‘,‘不存在‘) print(s) #便历 for i in s: print(i)
2.列表,元组,字典,集合的遍历。总结列表,元组,字典,集合的联系与区别。
#遍历列表 s=[‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘4‘,‘5‘] print("创建列表:") print(s) print("遍历列表:") for i in s: print(i) #遍历元祖 a=(‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘4‘,‘5‘) print("创建元祖:") print(s) print("遍历元祖:") for i in a: print(i) #遍历字典 c={} c[‘001‘]=60 c[‘002‘]=70 c[‘003‘]=80 c[‘004‘]=90 c[‘005‘]=100 print("创建字典:") print(c) print("遍历字典:") for i in c: print(i) #遍历集合 d=set(‘1452365478964‘) print("创建集合:") print(d) print("遍历集合:") for i in d: print(i)
Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。
另一种有序列表叫元组:tuple。tuple和list非常类似,但是tuple一旦初始化就不能修改。
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
3.英文词频统计实例
- 待分析字符串
- 分解提取单词
- 大小写 txt.lower()
- 分隔符‘.,:;?!-_’
- 单词列表
s=‘‘‘What Is Love-Kiesza Mmm.. Ooh.. I don‘t know you‘re not there. I give you my love, but you just don‘t care. Was I right, was I wrong. Give me a sign. What is love? Baby don‘t hurt me, don‘t hurt me, no more. What is love? Baby don‘t hurt me, dont hurt me, no more. Ooh ooh.. I don‘t know, what can I do? What can I say it‘s up to you. I know your right, just me and you. I can‘t go on. What is love? Baby don‘t hurt me, don‘t hurt me, no more. What is love? Baby don‘t hurt me, don‘t hurt me, no more, no more. Ooh, ooh... yeah.. Ooh, ooh, ooh... yeah I want no other, no other lover This is your life, but it‘s our time. But when we are together, I need you forever. Is this love? What is love? Baby don‘t hurt me, don‘t hurt me, no more. What is love? Baby don‘t hurt me, baby don‘t hurt me, no more, no more. don‘t hurt me, no more. Baby don‘t hurt me, no more... no more‘‘‘ print(‘单词出现的次数:‘) for i in ‘,.?!‘: s=s.replace(i,‘ ‘) s=str.lower(s) d={} b=s.split(‘ ‘) b.sort() e=set(b) for i in e: d[i]=0 for i in b: d[i]=d[i]+1 f=d.items() print(f)
时间: 2024-10-08 09:30:03