1. 字典实例:建立学生学号成绩字典,做增删改查遍历操作。
      ids=['01','11','21']
      scores=[85,90,65]
      
      dic={}
      dic['01']=scores[1]
      dic['11']=scores[0]
      dic['21']=scores[2]
      
      print(dic)
      print(dic.keys())
      print(dic.values())
      print(dic.items())
      
      print('输出值:',dic['11'])
      
      print('判断:','31'in dic)
      print('判断:','01'in dic)
      
      #
      dic['41']=75
      print('增加:',dic)
      
      #
      dic.pop('11')
      print('删除键11:',dic)
      #del(dic['11'])
      #print('删除key11:',dic)
      #print('删除key11:',dic.pop('11','不存在'))
      
      #
      dic['01']=100
      print('修改:',dic)
      
      print('获取:',dic.get('11','不存在'))
      print('获取:',dic.get('01','不存在'))

    2. 列表,元组,字典,集合的遍历。
      a=list('123')
      print('列表:',a)
      print('列表遍历:')
      for i in a:
          print(i)
      print()
      
      b=tuple('456')
      print('元组:',b)
      print('元组遍历:')
      for i in b:
          print(i)
      print()
      
      names=['Mary','Bob','Jhon']
      scores=[95,75,65]
      c={}
      c=dict(zip(names,scores))
      print('字典:',c)
      print('字典遍历:')
      for i in c:
          print(i,c[i])
      print()
      
      grades=['3','3','6','6','9','9']
      d=set(grades)
      print('集合:',d)
      print('集合遍历:')
      for i in d:
          print(i)

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

      组合数据类型:序列(列表list、元组tuple) 、集合set、字典dict(映射)                                                                                                                             

      列表:是一种有序的序列,可以随时添加和删除其中的元素,没有长度限制、元素类型可以不同。

      元组:和list非常相似,也是一种有序的序列,但是一旦初始化便不能修改。

      字典:使用键-值(key-value)进行存储,其中key必须为不可变的对象。比list占用空间大,具有极快的查找速度。

      集合:也是一组key的集合,但不存储value。由于key不能重复,所以在set中,没有重复的key。集合是无序的。

                 
    3. 英文词频统计实例
      1. 待分析字符串
      2. 分解提取单词
        1. 大小写 txt.lower()
        2. 分隔符'.,:;?!-_’
        3. 单词列表
      3. 单词计数字典
    4. str='''Where is the father?
      Two brothers were looking at some beautiful paintings.
      "Look," said the elder brother. "How nice these paintings are!"
      "Yes," said the younger, "but in all these paintings there is only the mother and the children.
      Where is the father?"
      The elder brother thought for a moment and then explained, "Obviously he was painting the pictures."'''
      
      print('原文:'+str+'\n')
      
      str=str.lower()
      print('所有大写转换为小写:'+str+'\n')
      
      for i in ',.?!"':
          str=str.replace(i,' ')
      print('所有分隔符替换为空格:'+str+'\n')
      
      print('统计单词father出现次数:',str.count('father'),'\n')
      
      words=str.split(' ')#分隔后的列表
      dict={}
      for i in words:
          dict[i]=words.count(i)
      items=list(dict.items())
      print('字典元组列表:',items,'\n')
      
      items.sort(key=lambda x:x[1],reverse=True)
      print('排序后出现次数前十的单词:')
      for i in range(10):
         print(items[i])

       

posted on 2017-09-26 13:26  077吴文欣  阅读(163)  评论(0编辑  收藏  举报