练习:
总结列表,元组,字典,集合的联系与区别。
列表,元组,字典,集合的遍历。
列表用[ ]创建,是可变的数据类型,可以被改变的,而且列表可以嵌套的。元组用()创建,元素之间用“,”分隔,不能修改元组,是不可变的。集合可以用set()函数或者{}创建,元素之间用“,”分隔,不可有重复元素;可以读写,是无序的。字典由key和值values组成;可以用dict()函数或者{}创建,元素之间用“,”分隔,键与值之间用":"分隔;键是唯一的、不可变的,值不要求,是无序的;用key来访问元素。
a = list('457451') #列表的遍历print(a)for i in a: print(i)b = tuple('485890') #元组的遍历print(b)for i in b: print(i)c = set('256156') #集合的遍历print(c)for i in c: print(i)d = { 'bob':80,'rose':79,'jack':90} #字典的遍历print(d)for i in d: print(i,d[i])
英文词频统计:
- 分隔出一个一个的单词 list
- 统计每个单词出现的次数 dict
str = '''I never knew,When the clock stopped and I'm looking at you, I never thought I'll miss someone like you, Someone I thought that I knew,I never knew, I should have known something wouldn't be true, Baby you know that I'm so into you, More than I know I should do'''#把单词全部变成小写a=str.lower()print(a)#去掉空格str=str.lstrip()print(str)#将歌词分隔出一个一个的单词listprint("将歌词分隔出一个一个的单词为:")strList=str.split()print(strList)#统计每个单词出现的次数print("统计每个单词出现的次数为:")strDict=set(strList)for word in strDict: print(word,strList.count(word))