基础数据类型(set集合)
认识集合
由一个或多个确定的元素所构成的整体叫做集合。
集合中的元素有三个特征:
1.确定性(集合中的元素必须是确定的)
2.互异性(集合中的元素互不相同。例如:集合A={1,a},则a不能等于1)
3.无序性(集合中的元素没有先后之分),如集合{3,4,5}和{3,5,4}算作同一个集合。
*集合概念存在的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中某个值
集合的定义
s = {1,2,3,1}
#定义可变集合
>>> set_test=set('hello')
>>> set_test
{'l', 'o', 'e', 'h'}
#改为不可变集合frozenset
>>> f_set_test=frozenset(set_test)
>>> f_set_test
frozenset({'l', 'e', 'h', 'o'})
集合的常用操作及关系运算
元素的增加
单个元素的增加 : add(),add的作用类似列表中的append
对序列的增加 : update(),而update类似extend方法,update方法可以支持同时传入多个参数:
>>> a={1,2}
>>> a.update([3,4],[1,2,7])
>>> a
{1, 2, 3, 4, 7}
>>> a.update("hello")
>>> a
{1, 2, 3, 4, 7, 'h', 'e', 'l', 'o'}
>>> a.add("hello")
>>> a
{1, 2, 3, 4, 'hello', 7, 'h', 'e', 'l', 'o'}
元素的删除
集合删除单个元素有两种方法:
元素不在原集合中时:
set.discard(x)不会抛出异常
set.remove(x)会抛出KeyError错误
>>> a={1,2,3,4}
>>> a.discard(1)
>>> a
{2, 3, 4}
>>> a.discard(1)
>>> a
{2, 3, 4}
>>> a.remove(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1
pop():由于集合是无序的,pop返回的结果不能确定,且当集合为空时调用pop会抛出KeyError错误,
clear():清空集合
>>> a={3,"a",2.1,1}
>>> a.pop()
1
>>> a.pop()
3
>>> a.clear()
>>> a
set()
>>> a.pop()
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 'pop from an empty set'
集合操作

|,|=:合集
a = {1,2,3}
b = {2,3,4,5}
print(a.union(b))
print(a|b)
&.&=:交集
a = {1,2,3}
b = {2,3,4,5}
print(a.intersection(b))
print(a&b)
-,-=:差集
a = {1,2,3}
b = {2,3,4,5}
print(a.difference(b))
print(a-b)
^,^=:对称差集
a = {1,2,3}
b = {2,3,4,5}
print(a.symmetric_difference(b))
print(a^b)
包含关系
in,not in:判断某元素是否在集合内
==,!=:判断两个集合是否相等
两个集合之间一般有三种关系,相交、包含、不相交。在Python中分别用下面的方法判断:
- set.isdisjoint(s):判断两个集合是不是不相交
- set.issuperset(s):判断集合是不是包含其他集合,等同于a>=b
- set.issubset(s):判断集合是不是被其他集合包含,等同于a<=b
集合的工厂函数
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): # real signature unknown
"""
Add an element to a set. This has no effect if the element is already present.
"""
pass def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. """
pass def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. """
pass def difference(self, *args, **kwargs): # real signature unknown
"""
相当于s1-s2 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): # real signature unknown
""" Remove all elements of another set from this set. """
pass def discard(self, *args, **kwargs): # real signature unknown
"""
与remove功能相同,删除元素不存在时不会抛出异常 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): # real signature unknown
"""
相当于s1&s2 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): # real signature unknown
""" Update a set with the intersection of itself and another. """
pass def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection. """
pass def issubset(self, *args, **kwargs): # real signature unknown
"""
相当于s1<=s2 Report whether another set contains this set. """
pass def issuperset(self, *args, **kwargs): # real signature unknown
"""
相当于s1>=s2 Report whether this set contains another set. """
pass def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
"""
pass def remove(self, *args, **kwargs): # real signature unknown
"""
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): # real signature unknown
"""
相当于s1^s2 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): # real signature unknown
""" Update a set with the symmetric difference of itself and another. """
pass def union(self, *args, **kwargs): # real signature unknown
"""
相当于s1|s2 Return the union of sets as a new set. (i.e. all elements that are in either set.)
"""
pass def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others. """
pass def __and__(self, *args, **kwargs): # real signature unknown
""" Return self&value. """
pass def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __iand__(self, *args, **kwargs): # real signature unknown
""" 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): # real signature unknown
""" Return self|=value. """
pass def __isub__(self, *args, **kwargs): # real signature unknown
""" Return self-=value. """
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __ixor__(self, *args, **kwargs): # real signature unknown
""" Return self^=value. """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __or__(self, *args, **kwargs): # real signature unknown
""" Return self|value. """
pass def __rand__(self, *args, **kwargs): # real signature unknown
""" Return value&self. """
pass def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __ror__(self, *args, **kwargs): # real signature unknown
""" Return value|self. """
pass def __rsub__(self, *args, **kwargs): # real signature unknown
""" Return value-self. """
pass def __rxor__(self, *args, **kwargs): # real signature unknown
""" Return value^self. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" S.__sizeof__() -> size of S in memory, in bytes """
pass def __sub__(self, *args, **kwargs): # real signature unknown
""" Return self-value. """
pass def __xor__(self, *args, **kwargs): # real signature unknown
""" Return self^value. """
pass __hash__ = None
基础数据类型(set集合)的更多相关文章
- WPF 绑定以基础数据类型为集合的无字段名的数据源
WPF 绑定以基础数据类型为集合的无字段名的数据源 运行环境:Window7 64bit,.NetFramework4.61,C# 6.0: 编者:乌龙哈里 2017-02-21 我们在控件的数据绑定 ...
- Python基础数据类型之集合
Python基础数据类型之集合 集合(set)是Python基本数据类型之一,它具有天生的去重能力,即集合中的元素不能重复.集合也是无序的,且集合中的元素必须是不可变类型. 一.如何创建一个集合 #1 ...
- Python基础数据类型之集合以及其他和深浅copy
一.基础数据类型汇总补充 list 在循环一个列表时,最好不要删除列表中的元素,这样会使索引发生改变,从而报错(可以从后向前循环删除,这样不会改变未删元素的索引). 错误示范: lis = [,,, ...
- 基础数据类型之集合和深浅copy,还有一些数据类型补充
集合 集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的.以下是集合最重要的两点: 去重,把一个列表变成集合,就自动去重了. 关系 ...
- Py西游攻关之基础数据类型(五)-集合
Py西游攻关之基础数据类型 - Yuan先生 https://www.cnblogs.com/yuanchenqi/articles/5782764.html 八 集合(set) 集合是一个无序的,不 ...
- 07、python的基础-->数据类型、集合、深浅copy
一.数据类型 1.列表 lis = [11, 22, 33, 44, 55] for i in range(len(lis)): print(i) # i = 0 i = 1 i = 2 del li ...
- Python - 基础数据类型 set 集合
集合的简介 集合是一个无序.不重复的序列 它的基本用法包括成员检测和消除重复元素 集合对象也支持像 联合,交集,差集,对称差分等数学运算 集合中所有的元素放在 {} 中间,并用逗号分开 集合的栗子 这 ...
- python的学习笔记01_4基础数据类型列表 元组 字典 集合 其他其他(for,enumerate,range)
列表 定义:[]内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素 特性: 1.可存放多个值 2.可修改指定索引位置对应的值,可变 3.按照从左到右的顺序定义列表元素,下标从0开始顺序访问 ...
- day 7 - 1 集合、copy及基础数据类型汇总
集合:{},可变的数据类型,他里面的元素必须是不可变的数据类型,无序,不重复.(不重要)集合的书写 set1 = set({1,2,3}) #set2 = {1,2,3,[2,3],{'name':' ...
随机推荐
- javaScript 基本知识点总结
1 javaScript 简介 JavaScript最初起源于LiveScript语言,当互联网开始流行时,越来越多的网站开始使用HTML表单与用户交互,然而表单交互却成了制约网络发展的重大瓶颈(用户 ...
- centos7命令行模式安装&&配置_br0+kvm+虚拟机+添加硬盘+快照及恢复
KVM创建虚拟机步骤 Submitted by zhaoley on October 18, 2016 - 10:43am 测试环境: 1: 43.243.130.89, CentOS Linux r ...
- 【213】IDL函数汇总
名称 功能说明 类型 语法&举例 IDL_VALIDNAME 判断变量名是否有效,无效返回值为空或者自动修改 函数 DEFSYSV 自定义系统变量,全局变量 过程 MAKE_ARRA ...
- 洛谷 - P1801 - 黑匣子 - 对顶堆
这道题是提高+省选-的难度,做出来的话对数据结构题目的理解会增加很多. 可以使用一种叫做对顶堆的东西,对顶堆是在线维护第n小的logn的算法.大概的思路是,假如我们要找的是第n小,我们就维护一个大小为 ...
- EOJ3263:丽娃河的狼人传说(贪心)
传送门 题意 分析 考虑将区间按右端点排序,再遍历区间,操作即可 建议以加方式写 trick 1.不需要判区间重合 代码 #include<cstdio> #include<cstr ...
- yield 为什么不能进入回调函数
操他妈的, allowed_domains = ['voice.hupu.com'] 这里面必须是域名,而不能是个路径,遇见问题不要瞎几把想,及时Google才是正道!!!!!!!!!11 感谢: h ...
- iOS 更改通知栏为白色
1.在 info.plist 中添加View controller-based status bar appearance,值为NO. 2.在设置状态栏的地方添加代码: UIApplication.s ...
- 跟我一起玩Win32开发(24):计时器
有好些时间没写博客了,今天要来耍一下计时器,就是我们常说的Timer,它虽然不是什么复杂的东西,也称不 上牛X,不过,用处还是不少的,对于那些需要每隔一定时间执行一次的任务,那是相当有用. 先来认识一 ...
- 数组Reduce的应用
数组Reduce的应用 参考 简单应用 var arr = [1,2,3,4,5] var sum = arr.reduce(function (prev, cur, index, arr) { co ...
- 在 CentOS 环境下安装 .NET Core
安装步骤: 参见官网 CentOS 会报以下错误: Error downloading packages: dotnet-runtime-2.2-2.2.4-1.x86_64: [Errno 256] ...