第三次作业

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

列表是以[ ]形式表示,元组是以( )表示,字典以{ }表示,集合则是以[()]的形式表示。列表(list),元组(tuple)是有序集合,tuple和list非常类似,但是tuple一旦初始化就不能修改而字典和集合是没顺序的。字典(dic)和集合(set)是无序的,dic是另一种可变容器模型,且可存储任意类型对象;set是一个无序不重复元素的序列。

 

列表,元组,字典,集合的遍历。

 

#列表的遍历

list = ['hello',11,'nihao',12]
print(list)
list.append('baby')
print(list)
list.pop(1)
print(list)
for i in list:
    print(i)

 

#元组的遍历

tuple = ('may','july',20,10)
print(tuple[2])
for i in tuple:
    print(i)

#字典的遍历

dic = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

print('Name:' , dic['Name'])
print('Age:', dic['Age'])

dic['Age'] = 8;  # 更新 Age
dic['School'] = "菜鸟教程"  # 添加信息

print('Age:', dic['Age'])
print('School:', dic['School'])

for key in dic:
    print(key,':',dic.get(key))

#集合的遍历

a = set([1,2,3])
print(a)

a.add(4)
print(a)
a.add('style')
print(a)

a.remove('style')
print(a)

for i in a:
    print(i)

英文词频统计:

  • 下载一首英文的歌词或文章str
  • 分隔出一个一个的单词 list
  • 统计每个单词出现的次数 dict
  • strStar=('''Twinkle, twinkle, little star,
    How I wonder what you are.
    Up above the world so high,
    Like a diamond in the sky.
    Twinkle, twinkle, little star,
    How I wonder what you are!
    When the blazing sun is gone,
    When he nothing shines upon,
    Then you show your little light,
    Twinkle, twinkle, all the night.
    Twinkle, twinkle, little star,
    How I wonder what you are!
    Then the traveler in the dark
    Thanks you for your tiny spark;
    He could not see which way to go,
    If you did not twinkle so.
    Twinkle, twinkle, little star,
    How I wonder what you are!
    Twinkle Twinkle Little Star ''')
    
    strgc = strStar.replace('.',' ')
    strList = strStar.split()
    print(len(strList),strList)     # 分隔一个单词并统计英文单词个数
    strSet = set(strList)           # 将列表转化成集合,再将集合转化成字典来统计每个单词出现个数
    print(strSet)
    strDict={ }
    for star in strSet:
        strDict[star] =strList.count(star)
    print(strDict,len(strDict))

posted @ 2018-09-22 15:56  a-庄儿  阅读(155)  评论(0编辑  收藏  举报