2021-11-08 理解map、set、zip的用法
1. set(集合)
作用:可以操作list,str等格式,set类型有很好的不重复性,可以用来去重。可以理解为数学学过的集合。比如交集、并集、差集(补集)等。
- 请一定记住在set中:
1.无序!!!!!!!!!!!
2.元素不可变!!!!!!!!!!
痛苦:比较痛苦的是,作为一个无序的集合,不支持 index,不记录元素位置与插入点,所以没有办法向固定位置插入或者删除元素。同业也不处置序列操作(一般序列操作都有index)
实现原理:python中set的C语言源码就不po了吗,需要知道的是,为了提高查询速度使用的也是哈希表,但是与字典结构(dict)有所不同(只能看出不同,不知道区分)。对应的set值的存储是通过结构体setentry来保存数值的。
typedef struct {
PyObject *key;
Py_hash_t hash; /* Cached hash code of the key */
} setentry;
从代码中可以看出,key是保存的数据,hash就是对应数据的hash,下面是PyObject的结构体实现
typedef struct {
PyObject_HEAD
Py_ssize_t fill; /* Number active and dummy entries*/ // 包括已经使用的entry与空entry值的总和
Py_ssize_t used; /* Number active entries */ // 已经使用可用的总量
/* The table contains mask + 1 slots, and that's a power of 2.
* We store the mask instead of the size because the mask is more
* frequently needed.
*/
Py_ssize_t mask; // 与hash求和的mask
/* The table points to a fixed-size smalltable for small tables
* or to additional malloc'ed memory for bigger tables.
* The table pointer is never NULL which saves us from repeated
* runtime null-tests.
*/
setentry *table; // 保存数据的数组数组指针
Py_hash_t hash; /* Only used by frozenset objects */
Py_ssize_t finger; /* Search finger for pop() */
setentry smalltable[PySet_MINSIZE]; // 保存数据的数组 默认初始化为8个元素,通过table指向
PyObject *weakreflist; /* List of weak references */
} PySetObject;
set命令合集:
set() 定义一个初始空集合
a & b 交集
a | b 并集
a - b 差集
a.union(b) 并集
a.intersection(b) 交集
a.difference(b) 差集,a中有但是b中没有的元素合集
a.issubset(b) 测试是否 a 中的每一个元素都在 b 中,运算符操作为 s1<=s2
a <= b 测试 a是否为b的子集
b.issuperset(a) uper set 懂得都懂了嘛,就是b是不是a得父集?随便一叫
b >= a 测试 b是否为a的父集
🚀️ 插入、删除、更新等操作
add() 插入一个元素
remove() 删除一个元素,必须存在不存在会报 KeyError
update() 更新,就是原来有一个
discard() 用于删除一个set中的元素,这个值不必一定存在,不存在的情况下删除也不会触发错误。
clear() 清空
if all(key in set1 for key in set2): 随便举个迭代的例子
使用示例:
###----------------------------------->以arr_list =[1,1,2,3,4,4,5,6,6]为例
arr_list = [1,1,2,3,4,4,5,6,6]
#*---------------------------------------------------------------------*#
arr_set = set(arr_list)
#[]:arr_set:{1,2,3,4,5,6}
arr_set.add(3) ###添加已有元素不变
#[]:arr_set:{1,2,3,4,5,6}
arr_set.add(7)
#[]:arr_set:{1,2,3,4,5,6,7} ###添加set中不E的key
##可以看出add的本质其实还是key能否被hash,add('qq')也可以
####remove,update操作就不记录了