1.字典实例:建立学生学号成绩字典,做增删改查遍历操作。

dict={'001':'66','003':'77','006':'88','009':'99'}
print('学生学号成绩:',dict)

dict['007']=96
print('增加学号为007的学生的成绩为96:',dict)

dict.pop('001')
print('删除学号为001的学生的记录:',dict)

dict['007']=100
print('修改学号为007的学生的成绩为100:',dict)

print('查找学号为002的学生的记录:',dict.get('002'))

运行结果如图:

 

2.(1)列表,元组,字典,集合的遍历。

nums=('123456')
words=('family')
list=list('23333')

tu=tuple('bigfish')
s=set(list)
dict=dict(zip(nums,words))
print(dict)
print('打印列表')
for i in list:
    print(i)
print('打印字典')
for j in dict:
     print(j,dict[j])
print('打印元组')
for i in tu:
    print(i)
print('打印集合')
for i in s:
    print(i)

运行结果如图:

(2)总结列表,元组,字典,集合的联系与区别。

答:list是一种有序的序列,正向递增、反向递减序号。可以随时添加和删除其中的元素,没有长度限制,元素类型可以不同。

       tuple和list非常类似,都是有序的序列。但是tuple一旦初始化就不能修改。

      dict使用键-值(key-value)存储,key是不可变的对象。插入和查找速度快,不会随着key的增加而变慢,需要占用大量的内存。dict是用空间换取时间的一种方法。

     集合(set)则是一组key的无序集合,但是它只包含key,key值不能够重复,并且需要先创建一个List作为输入集合才能继续创建set。

 

3.英文词频统计实例

  1. 待分析字符串
  2. 分解提取单词单词计数字典
    1. 大小写 txt.lower()
    2. 分隔符'.,:;?!-_’
    3. 单词列表
      w ='''London bridge is falling down, 
      falling down, falling down. 
      London bridge is falling down, 
      my fair lady . 
      Build it up with iron bars, 
      iron bars, iron bars. 
      Build it up with iron bars, 
      my fair lady. 
      Iron bars will bend and break , 
      bend and break, bend and break. 
      Iron bars will bend and break, 
      my fair lady. '''
      
      w = w.lower()
      for i in ',.':
          w=w.replace(i,' ')
      songs=w.split(' ')
      print('分割替换后的歌词为: '+str(songs))
      
      
      ##定义字典#
      d={}
      
      #写入字典#
      di=set(songs)
      for i in di:
          d[i]=0
      for i in songs:
          d[i]=d[i]+1
      
      print("单词列表:"+str(d.items()))

posted on 2017-09-26 17:38  094吴嘉绿  阅读(136)  评论(0编辑  收藏  举报