Python基本数据类型之set

一、定义

set是一个无序且不重复的元素集合。

集合对象是一组无序排列的可哈希的值,集合成员可以做字典中的键。集合支持用in和not in操作符检查成员,由len()内建函数得到集合的基数(大小), 用 for 循环迭代集合的成员。但是因为集合本身是无序的,不可以为集合创建索引或执行切片(slice)操作,也没有键(keys)可用来获取集合中元素的值。

set和dict一样,只是没有value,相当于dict的key集合,由于dict的key是不重复的,且key是不可变对象因此set也有如下特性:

  1. 不重复

  2. 元素为不可变对象

二、创建


s = set()
s = {11,22,33,44}  #注意在创建空集合的时候只能使用s=set(),因为s={}创建的是空字典

a=set('boy')
b=set(['y', 'b', 'o','o']) c=set({"k1":'v1','k2':'v2'}) d={'k1','k2','k2'} e={('k1', 'k2','k2')} print(a,type(a)) print(b,type(b)) print(c,type(c)) print(d,type(d)) print(e,type(e)) OUTPUT: {'o', 'b', 'y'} <class 'set'> {'o', 'b', 'y'} <class 'set'> {'k1', 'k2'} <class 'set'> {'k1', 'k2'} <class 'set'> {('k1', 'k2', 'k2')} <class 'set'>

三、基本操作

比较


se = {11, 22, 33}
be = {22, 55}
temp1 = se.difference(be)        #找到se中存在,be中不存在的集合,返回新值
print(temp1)        #{33, 11}
print(se)        #{33, 11, 22}temp2 = se.difference_update(be) #找到se中存在,be中不存在的集合,覆盖掉se
print(temp2)        #None print(se) #{33, 11}, 

删除

discard()、remove()、pop()


se = {11, 22, 33}
se.discard(11)
se.discard(44)  # 移除不存的元素不会报错
print(se)se = {11, 22, 33}
se.remove(11)
se.remove(44)  # 移除不存的元素会报错
print(se)se = {11, 22, 33}  # 移除末尾元素并把移除的元素赋给新值
temp = se.pop()
print(temp)  # 33
print(se) # {11, 22} 

取交集


se = {11, 22, 33}
be = {22, 55}temp1 = se.intersection(be)             #取交集,赋给新值
print(temp1)  # 22
print(se)  # {11, 22, 33}temp2 = se.intersection_update(be)      #取交集并更新自己
print(temp2)  # None print(se) # 22

判断


se = {11, 22, 33}
be = {22}print(se.isdisjoint(be))        #False,判断是否不存在交集(有交集False,无交集True)
print(se.issubset(be))          #False,判断se是否是be的子集合
print(se.issuperset(be))        #True,判断se是否是be的父集合

合并


se = {11, 22, 33}
be = {22}temp1 = se.symmetric_difference(be)  # 合并不同项,并赋新值
print(temp1)    #{33, 11}
print(se)       #{33, 11, 22}temp2 = se.symmetric_difference_update(be)  # 合并不同项,并更新自己
print(temp2)    #None print(se) #{33, 11} 

取并集


se = {11, 22, 33}
be = {22,44,55}temp=se.union(be)   #取并集,并赋新值
print(se)       #{33, 11, 22}
print(temp)     #{33, 22, 55, 11, 44}

更新


se = {11, 22, 33}
be = {22,44,55}se.update(be)  # 把se和be合并,得出的值覆盖se
print(se)
se.update([66, 77])  # 可增加迭代项
print(se)

集合的转换


se = set(range(4))
li = list(se)
tu = tuple(se)
st = str(se) print(li,type(li)) print(tu,type(tu)) print(st,type(st)) OUTPUT: [0, 1, 2, 3] <class 'list'> (0, 1, 2, 3) <class 'tuple'> {0, 1, 2, 3} <class 'str'>

四、源码


class set(object):""" set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. """ def add(self, *args, **kwargs): """添加""" """ Add an element to a set. This has no effect if the element is already present. """ pass def clear(self, *args, **kwargs): """清除""" """ Remove all elements from this set. """ pass def copy(self, *args, **kwargs): """浅拷贝""" """ Return a shallow copy of a set. """ pass def difference(self, *args, **kwargs): """比较""" """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass def difference_update(self, *args, **kwargs): """ Remove all elements of another set from this set. """ pass def discard(self, *args, **kwargs): """删除""" """ Remove an element from a set if it is a member. If the element is not a member, do nothing. """ pass def intersection(self, *args, **kwargs): """ Return the intersection of two sets as a new set. (i.e. all elements that are in both sets.) """ pass def intersection_update(self, *args, **kwargs): """ Update a set with the intersection of itself and another. """ pass def isdisjoint(self, *args, **kwargs): """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): """ Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): """ Report whether this set contains another set. """ pass def pop(self, *args, **kwargs): """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. """ pass def remove(self, *args, **kwargs): """ Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ pass def symmetric_difference(self, *args, **kwargs): """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass def symmetric_difference_update(self, *args, **kwargs): """ Update a set with the symmetric difference of itself and another. """ pass def union(self, *args, **kwargs): """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass def update(self, *args, **kwargs): """ Update a set with the union of itself and others. """ pass def __and__(self, *args, **kwargs): """ Return self&value. """ pass def __contains__(self, y): """ x.__contains__(y) <==> y in x. """ pass def __eq__(self, *args, **kwargs): """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): """ Return getattr(self, name). """ pass def __ge__(self, *args, **kwargs): """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): """ Return self>value. """ pass def __iand__(self, *args, **kwargs): """ Return self&=value. """ pass def __init__(self, seq=()): # known special case of set.__init__ """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. # (copied from class doc) """ pass def __ior__(self, *args, **kwargs): """ Return self|=value. """ pass def __isub__(self, *args, **kwargs): """ Return self-=value. """ pass def __iter__(self, *args, **kwargs): """ Implement iter(self). """ pass def __ixor__(self, *args, **kwargs): """ Return self^=value. """ pass def __len__(self, *args, **kwargs): """ Return len(self). """ pass def __le__(self, *args, **kwargs): """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): """ Return self<value. """ pass  @staticmethod def __new__(*args, **kwargs): """ Create and return a new object. See help(type) for accurate signature. """ pass def __ne__(self, *args, **kwargs): """ Return self!=value. """ pass def __or__(self, *args, **kwargs): """ Return self|value. """ pass def __rand__(self, *args, **kwargs): """ Return value&self. """ pass def __reduce__(self, *args, **kwargs): """ Return state information for pickling. """ pass def __repr__(self, *args, **kwargs): """ Return repr(self). """ pass def __ror__(self, *args, **kwargs): """ Return value|self. """ 

转载于:https://www.cnblogs.com/xwqhl/p/10690903.html

Python基本数据类型之set相关推荐

  1. Python的零基础超详细讲解(第四天)-Python的数据类型

    Python 基本数据类型 Python 中的变量不需要声明.每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建. 在 Python 中,变量就是变量,它没有类型,我们所说的"类型&q ...

  2. python的数据类型和变量

    python的数据类型和变量 数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频.网页等各种 ...

  3. python核心数据类型_Python核心数据类型-列表

    Python核心数据类型-列表 关于列表的重要属性 列表是任意对象的有序集合,列表中可以包含任何种类的对象,数字 字符串 或者是其他列表 列表可以通过偏移来读取其中的元素,也可以通过分片读取列表中的某 ...

  4. python判断数据类型type_Python 判断数据类型有type和isinstance

    Python 判断数据类型有type和isinstance 基本区别在于: type():不会认为子类是父类 isinstance():会认为子类是父类类型 执行结果如下: 用isinstance判断 ...

  5. Python基础数据类型之set集合

    Python基础数据类型之set集合 一.set数据类型介绍 二.set集合演示 三.set集合中hash介绍 1.哈希定义 2.数据类型的hash和不可hash 3.set中hash示例 四.set ...

  6. Python基础数据类型之字符串(二)

    Python基础数据类型之字符串(二) 一.字符串的常规操作 二.字符串的大小写转换 1.首字母大写 2. 每个单词首字母大写 3.大写转化为小写 4.所有字母变成大写字母 二.验证码忽略大小写 三. ...

  7. Python基础数据类型之字符串(一)

    Python基础数据类型之字符串(一) 一.字符串格式化 1.字符串占位符 2.字符串格式化操作 二.f-string格式化 三.字符串的索引 四.字符串的切片 1.常规切片使用方法 3.步长的介绍 ...

  8. 好好学python·基本数据类型

    好好学Python的第一天 基本用法 注释 输出 变量 命名规范 变量的定义方式 python的数据类型 数据类型分类 字符串类型 数字类型 List列表类型 tuple 元组类型的定义 Dict字典 ...

  9. python元组类型_什么是python元组数据类型

    什么是python元组数据类型 发布时间:2020-08-25 11:46:29 来源:亿速云 阅读:68 这篇文章运用简单易懂的例子给大家介绍什么是python元组数据类型,代码非常详细,感兴趣的小 ...

  10. python核心数据类型_Python核心数据类型—元组

    Python核心数据类型-元组 Python元组与列表类似,但是元组属于不可变类型 创建元组 a = () #创建空元组 a = (1, 2, 3) #创建一个元组 a = [1, 2, 3] b = ...

最新文章

  1. 使用feign调用注解在eureka上的微服务,简单学会微服务
  2. 搭建WordPress博客平台,云计算技术与应用实验报告
  3. return 函数
  4. 逻辑地址、线性地址、物理地址和虚拟地址初步认识
  5. 【转载保存】lucene正则查询使用注意
  6. 【AD】AD19/20笔记及快捷键
  7. 299. Bulls and Cows
  8. jdbc数据源连接oracle,请教JDBC怎么连接ORACLE数据库
  9. WinRAR注册+去广告教程
  10. 【Unity3D插件】FancyScrollView插件分享《通用UI滑动列表》
  11. 苏州大学计算机考研资料汇总
  12. excel技巧——F9键
  13. 升级IOS百度人脸SDK4.0采坑记录
  14. 致老友-有时候我词不达意 但我真的很开心生活有你
  15. uefi怎么念_UEFI模式和32位64位系统安装的简单说明
  16. SLIC算法理解(仅为个人笔记)
  17. 关于 Java 的线程状态
  18. [本周总结并查集,搜索]
  19. OWC11绘制双轴图表
  20. Crow:hello world

热门文章

  1. TypeScript算法专题 - blog2 - 单链表节点的索引、结点删除与链表反转
  2. 永恒python怎么用_毫无基础的人如何入门 Python ?Python入门教程拿走不谢啦!
  3. Nonebot部署机器人常见问题
  4. Linux 基本命令不能用的解决方法
  5. 单点登录有关跨域的点
  6. 笔记(2)-文本挖掘与机器学习
  7. VirtualApp实战之拿到女神朋友圈封面
  8. Vue : Expected the Promise rejection reason to be an Error
  9. angular2系列之动画-路由转场动画
  10. mysql的配置文件适用5.6与5.7