当前位置:网站首页>第027讲:集合:在我的世界里,你就是唯一 | 课后测试题及答案
第027讲:集合:在我的世界里,你就是唯一 | 课后测试题及答案
2022-06-22 20:05:00 【ChaseTimLee】
测试题:
0. 请问集合的唯一作用是什么呢?
答:集合几乎所有的作用就是确保里边包含的元素的唯一性,就像世界上没有两片完全相同的树叶一样,集合内不可能存在两个相同的元素!
1. 如果你希望创建的集合是不变的,应该怎么做?
答:frozenset()
2. 请问如何确定一个集合里边有多少个元素?
答:没错,len()函数正好可以满足你此刻的需求_
3. 请目测以下代码会打印什么内容?
>>> num_set = set([1, 2, 3, 4, 5])
>>> num_set[0]
答:会报错,因为集合是无序的。
4. 请问 set1 = {[1, 2]} 和 set1 = set([1, 2]) 执行的结果一样吗?
答:不一样,set1 = set([1, 2]) 会生成一个集合{1, 2},但set1 = {[1, 2]}却会报错。
从报错信息上我们看到“列表不是可哈希类型”,没错,列表是可变的,它怎么可以哈希呢?!咦,等等,这句话好像在那听过……呃,敢情集合跟字典的存储方式一样的丫!
其实你再想想就会觉得很有道理,利用哈希函数计算,相同的元素得到的哈希值(存放地址)是相同的,所以在集合中所有相同的元素都会覆盖掉,因此有了集合的唯一性。
然后你继续接着想就觉得更有道理了,通过哈希函数计算的地址不可能是按顺序排放的,所以集合才强调是无序的!
5. 打开你的IDLE,输入set1 = {1, 1.0},你发现了什么?
答:没错, 集合内容是{1.0},其实你弄懂了上一题,这一题一样容易:因为在Python的哈希函数会将相同的值的元素计算得到相同的地址,所以1和1.0是等值的
6. 请问如何给集合添加和删除元素?
答:使用add()方法可以为集合添加元素,使用remove()方法可以删除集合中已知的元素。
>>> num1.add(6)
>>> num1
{
0, 1, 2, 3, 4, 5, 6}
>>> num1.remove(6)
>>> num1
{
0, 1, 2, 3, 4, 5}
边栏推荐
- 2022年起重机械指挥考试模拟100题及模拟考试
- [palindrome structure of or36 linked list]
- 5分钟快速上线Web应用和API(Vercel)
- Learning websites that programmers must see
- [redis]集群与常见错误
- Extended ribbon supports metadata based version management
- 查看苹果产品保修状态
- 75- when left join encounters subquery
- 2022 a special equipment related management (elevator) examination questions and simulation examination
- ACM. HJ45 名字的漂亮度 ●●
猜你喜欢
![[redis]发布与订阅](/img/50/0c2fbbb8f56fccdd3222b77efdd723.png)
[redis]发布与订阅

长安旗下阿维塔科技增资扩股落定:宁德时代将持股约24%!

2022 chemical automation control instrument examination exercises and online simulation examination

ByteDance proposes a lightweight and efficient new network mocovit, which has better performance than GhostNet and mobilenetv3 in CV tasks such as classification and detection

Ultrafast transformers | redesign vit with res2net idea and dynamic kernel size, surpassing mobilevit

【206. 反转链表】

【138. 复制带随机指针的链表】

Laravel+ pagoda planning task

【ICML2022】利用虚拟节点促进图结构学习

las 点云创建网格
随机推荐
2022年起重机械指挥考试模拟100题及模拟考试
Apple corefoundation source code
软考必备资料大放送,全科目软考资料都给你备好了!
redis学习笔记
超快变形金刚 | 用Res2Net思想和动态kernel-size再设计 ViT,超越MobileViT
[redis]三种新数据类型
74- how to remedy the loss of Oracle to MySQL for this kind of SQL optimization?
R language airpassengers dataset visualization
78- several methods to solve SQL performance problems without changing code in production system
[redis]集群与常见错误
How swiftui simulates the animation effect of view illumination increase
[redis]Redis6的主从复制
嵌入式开发基础之任务管理(线程管理)
[redis]redis6 transaction operations
RealNetworks vs. 微软:早期流媒体行业之争
[the penultimate node in the linked list]
Baijia forum in the 13th year of Yongzheng (lower part)
[redis]配置文件
杰理之外挂 4M 的 flash 在 PC 上查看大小只有 1M 的处理方法【篇】
las 点云创建网格