组合数据类型练习,英文词频统计实例上

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

 

stu=['张三','李四','王五','刘六']
gra=[99,98,97,96]
d=dict(zip(stu,gra))
d['小梁']=90
d.pop('刘六')
d['王五']=89
d.get('张三')
print(d)

2.列表、元组、字典、集合的遍历

lis = list('23132111123132')

tup = tuple('1233211232123')

s = set(l)

d = dict(zip([1,2,3,4],[4,3,2,1]))

for i in lis:

    print(i)

for i in tup:

    print(i)

for i in s:

    print(i)

for i in d:

    print(i)

3.总结列表、元组、字典、集合的联系与区别

(1)列表是可变对象,它支持在原处修改的操作.也可以通过指定的索引和分片获取元素。区别于元组,可动态增加,删除,更新。

(2)元组和列表在结构上没有什么区别,唯一的差异在于元组是只读的,不能修改,元组一旦定义其长度和内容都是固定的。

一旦创建元组,则这个元组就不能被修改,即不能对元组进行更新、增加、删除操作。

(3)集合没有特殊的表示方法,而是通过一个set函数转换成集合。集合是一个无序不重复元素集,基本功能包括关系测试和消除重复元素.。

(4)字典存储键值对数据,字典最外面用大括号,每一组用冒号连起来,然后各组用逗号隔开,字典最大的价值是查询,通过键,查找值。字典和集合都是无序的。

实例:词频统计

song='''It's amazing how you can speak right to my heart
Without saying a word,
you can light up the dark
Try as I may I could never explain
What I hear when you don't say a thing
The smile on your face lets me know that you need me
There's a truth in your eyes saying you'll never leave me
The touch of your hand says you'll catch me whenever I fall
You say it best.. when you say nothing at all
All day long I can hear people talking out loud
But when you hold me near, you drown out the crowd
Try as they may they can never define
What's been said between your heart and mine
The smile on your face lets me know that you need me
There's a truth in your eyes saying you'll never leave me
The touch of your hand says you'll catch me whenever I fall
You say it best.. when you say nothing at all
The smile on your face lets me know that you need me
There's a truth in your eyes saying you'll never leave me
The touch of your hand says you'll catch me whenever I fall
You say it best.. when you say nothing at all'''

song=song.replace(',',' ')
song=song.replace('.',' ')
song=song.replace('\n',' ')
song=song.lower()
words=song.split(' ')

dic={}
words.sort()
di=set(words)

for i in di:
    dic[i]=0  //循环插入值为空的主键i

for i in words:
      dic[i]=dic[i]+1//利用循环计算主键个数

items=dic.items()

print(items)

 

posted @ 2017-09-22 12:10  yishhaoo  阅读(155)  评论(0编辑  收藏  举报