【Python】七、字典与集合的应用


实验目的

  1. 掌握字典与集合的定义和使用;
  2. 培养学生动手查阅资料能力和解决实际问题的能力和团队合作能力。

一、字典的定义

       字典是另一种可变容器模型,且可存储任意类型对象。
       字典的每个键值 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))

实验截图

在这里插入图片描述


  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慢热型网友.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值