当前位置:网站首页>第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}
边栏推荐
- [Jianzhi offer] interview question 44 A digit in a sequence of numbers
- 杰理之MUSIC 模式获取播放文件的目录【篇】
- Moke 5. Service discovery -nacos
- 杰理之硬件上 DACL 输出,DAC 输出左右声道的声音【篇】
- Pytorch's model saving, loading and continuing training
- [redis]三种新数据类型
- PHP image making
- NBA季后赛对阵图
- Redis learning notes
- CVPR2022 | 海德堡大学《深度视觉相似性与度量学习》教程
猜你喜欢

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

NumPy学习笔记(六)——sum()函数
![[cm11 linked list splitting]](/img/66/6ac3f78db20ec7f177b88c88028dde.png)
[cm11 linked list splitting]

2022 a special equipment related management (elevator) examination questions and simulation examination
![[redis] profile](/img/1c/05c06d59c9efb5983f877822db333c.png)
[redis] profile

杰理之外挂 4M 的 flash 在 PC 上查看大小只有 1M 的处理方法【篇】
![[redis] publish and subscribe](/img/50/0c2fbbb8f56fccdd3222b77efdd723.png)
[redis] publish and subscribe

ICML2022 | 利用虚拟节点促进图结构学习
![[redis]redis的持久化操作](/img/83/9af9272bd485028062067ee2d7a158.png)
[redis]redis的持久化操作

【160. 相交链表】
随机推荐
Evaluation index and code realization (ndcg)
苹果CoreFoundation源代码
[palindrome structure of or36 linked list]
杰理之AUX 模式使用 AUX1或者 AUX2通道时,程序会复位问题【篇】
杰理之动态切换 EQ 文件【篇】
2022 group programming TIANTI race L1
百家讲坛 雍正十三年(下部)
查看苹果产品保修状态
[redis] cluster and common errors
Redis learning notes
ICML2022 | 利用虚拟节点促进图结构学习
百家讲坛 黄帝内经(第一部)
[redis]集群与常见错误
Correspondence between int and char in C language
53 page intelligent campus intelligent system design scheme (download attached)
Fluent system architecture
C语言中int和char的对应关系
牛客 52次月赛 B牛牛的身高 (思维题 模拟题)
[cm11 linked list splitting]
MySQL adds (appends) prefix and suffix to a column field