实验目的
- 掌握字典与集合的定义和使用;
- 培养学生动手查阅资料能力和解决实际问题的能力和团队合作能力。
一、字典的定义
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值 key:value 对用冒号 : 分割,每个键值对之间用逗号 , 分割,整个字典包括在花括号 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2 }
注意:dict 作为 Python 的关键字和内置函数,变量名不建议命名为 dict。键一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
二、集合的定义
集合(set)是一个无序的不重复元素序列。可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
三、集合的基本操作
# 添加元素.
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{'Taobao', 'Facebook', 'Google', 'Runoob'}
>>> s.update( x )
# 2、移除元素
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.remove("Taobao")
>>> print(thisset)
{'Google', 'Runoob'}
# 计算集合元素个数
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> len(thisset)
3
# 清空集合
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.clear()
>>> print(thisset)
set()
#判断元素是否在集合中存在
>>> thisset = set(("Google", "Runoob", "Taobao"))
>>> "Runoob" in thisset
True
>>> "Facebook" in thisset
False
四、编写程序,实现用户随机输入一段话,统计本段话的高频词汇
参考代码
"""Count words."""
def count_words(s, n):
w = {}
sp = s.split()
for i in sp:
if i not in w:
w[i] = 1
else:
w[i] += 1
top = sorted(w.items(), key=lambda item: (-item[1], item[0]))
top_n = top[:n]
return top_n
print("cat bat mat cat bat cat中的高频词汇:")
print(count_words("cat bat mat cat bat cat", 3))
print("betty bought a bit of butter but the butter was bitter中的高频词汇:")
print(count_words("betty bought a bit of butter but the butter was bitter", 3))