一、定义

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. """
pass def __rsub__(self, *args, **kwargs):
""" Return value-self. """
pass def __rxor__(self, *args, **kwargs):
""" Return value^self. """
pass def __sizeof__(self):
""" S.__sizeof__() -> size of S in memory, in bytes """
pass def __sub__(self, *args, **kwargs):
""" Return self-value. """
pass def __xor__(self, *args, **kwargs):
""" Return self^value. """
pass __hash__ = None

Python基本数据类型之set的更多相关文章

  1. python 基本数据类型分析

    在python中,一切都是对象!对象由类创建而来,对象所拥有的功能都来自于类.在本节中,我们了解一下python基本数据类型对象具有哪些功能,我们平常是怎么使用的. 对于python,一切事物都是对象 ...

  2. python常用数据类型内置方法介绍

    熟练掌握python常用数据类型内置方法是每个初学者必须具备的内功. 下面介绍了python常用的集中数据类型及其方法,点开源代码,其中对主要方法都进行了中文注释. 一.整型 a = 100 a.xx ...

  3. 闲聊之Python的数据类型 - 零基础入门学习Python005

    闲聊之Python的数据类型 让编程改变世界 Change the world by program Python的数据类型 闲聊之Python的数据类型所谓闲聊,goosip,就是屁大点事可以咱聊上 ...

  4. python自学笔记(二)python基本数据类型之字符串处理

    一.数据类型的组成分3部分:身份.类型.值 身份:id方法来看它的唯一标识符,内存地址靠这个查看 类型:type方法查看 值:数据项 二.常用基本数据类型 int 整型 boolean 布尔型 str ...

  5. Python入门-数据类型

    一.变量 1)变量定义 name = 100(name是变量名 = 号是赋值号100是变量的值) 2)变量赋值 直接赋值 a=1 链式赋值  a=b=c=1 序列解包赋值  a,b,c = 1,2,3 ...

  6. Python基础:八、python基本数据类型

    一.什么是数据类型? 我们人类可以很容易的分清数字与字符的区别,但是计算机并不能,计算机虽然很强大,但从某种角度上来看又很傻,除非你明确告诉它,"1"是数字,"壹&quo ...

  7. python之数据类型详解

    python之数据类型详解 二.列表list  (可以存储多个值)(列表内数字不需要加引号) sort s1=[','!'] # s1.sort() # print(s1) -->['!', ' ...

  8. Python特色数据类型(列表)(上)

    Python从零开始系列连载(9)——Python特色数据类型(列表)(上) 原创 2017-10-07 王大伟 Python爱好者社区 列表 列表,可以是这样的: 分享了一波我的网易云音乐列表 今天 ...

  9. 【Python】-NO.97.Note.2.Python -【Python 基本数据类型】

    1.0.0 Summary Tittle:[Python]-NO.97.Note.2.Python -[Python 基本数据类型] Style:Python Series:Python Since: ...

  10. python基本数据类型之集合

    python基本数据类型之集合 集合是一种容器,用来存放不同元素. 集合有3大特点: 集合的元素必须是不可变类型(字符串.数字.元组): 集合中的元素不能重复: 集合是无序的. 在集合中直接存入lis ...

随机推荐

  1. 吉特仓库管理系统-.SQL Server 2012 升级企业版

    随着业务数据的不断增大,单表的数量已经上亿,查询的数据越来越慢,所以考虑到将数据库表分区,同时也将数据库升级到SQL Server 2012. 当时没有考虑更多,在服务器上安装了 SQL Server ...

  2. Learning to Rank 简介

    转自:http://www.cnblogs.com/kemaswill/archive/2013/06/01/3109497.html,感谢分享! 本文将对L2R做一个比较深入的介绍,主要参考了刘铁岩 ...

  3. javascript 连等赋值问题(这是从SegmentFault转过来的一个问题)

    var a = {n:1}; var b = a; // 持有a,以回查 a.x = a = {n:2}; alert(a.x);// --> undefined alert(b.x);// - ...

  4. C# has three timers

    结论 *1.窗体timer和线程timer.计时器timer不同,因为后两者dispose之后,GC可以收集,而前者无法收集 *2.如果一个对象的成员函数正在被执行,那么这个对象肯定不会被收集 *3. ...

  5. RHCE认证考试教材

    前段时间考RHCE7,顺便给大家分享下RHCE6.7的中文教材!毕竟此书是官方的培训教材,还是值得看看!RHEL6.7承前启后的,给个赞! 下载:http://pan.baidu.com/s/1nu9 ...

  6. 十天冲刺---Day9

    站立式会议 站立式会议内容总结: 燃尽图 照片 队员们都回来了,写完之后继续对alpha版本进行迭代. 希望演示的时候能拿得出来.

  7. xml文件的生成与解析

    生成方法一:同事StringBuffer类对xml文件格式解析写入 package com.steel_rocky.xml; import android.app.Activity; import a ...

  8. html5 播放多个视频。一个接一个的播放

    new个video,指定播放列表的第一个视频路径为src.监听end事件,回调里面把video的src改成列表的下一个,再play. 示意代码:var vList = ['视频地址url1', 'ur ...

  9. nginx--配置https服务器

    1.下载安装nginx: nginx可以从这里选择对应版本下载,我下载的是1.8.1版本.下载完成后,直接解压缩,命令窗口进入根目录,输入命令: start nginx 在浏览器中,直接输入" ...

  10. ASP.NET MVC 4 异步加载控制器

    ASP.NET 4 Developer preview中的异步操纵器 在放弃了对.NET 3的支持之后, ASP.NET MVC 4 彻底拥抱了Task类库, 你不需求再蛋疼的给每个Action写两个 ...