浅谈Python 集合(set)类型的操作——并交差

yipeiwu_com6年前Python基础

阅读目录

•介绍
•基本操作
•函数操作

介绍

python的set是一个无序不重复元素集,基本功能包括关系测试和消除重复元素. 集合对象还支持并、交、差、对称差等。

sets 支持 x in set、 len(set)、和 for x in set。作为一个无序的集合,sets不记录元素位置或者插入点。因此,sets不支持 indexing, slicing, 或其它类序列(sequence-like)的操作。

基本操作

>>> x = set("jihite")
>>> y = set(['d', 'i', 'm', 'i', 't', 'e'])
>>> x    #把字符串转化为set,去重了
set(['i', 'h', 'j', 'e', 't'])
>>> y
set(['i', 'e', 'm', 'd', 't'])
>>> x & y  #交
set(['i', 'e', 't'])
>>> x | y  #并
set(['e', 'd', 'i', 'h', 'j', 'm', 't'])
>>> x - y  #差
set(['h', 'j'])
>>> y - x
set(['m', 'd'])
>>> x ^ y  #对称差:x和y的交集减去并集
set(['d', 'h', 'j', 'm'])

函数操作

 

>>> x
set(['i', 'h', 'j', 'e', 't'])
>>> s = set("hi")
>>> s
set(['i', 'h'])
>>> len(x)          #长度

>>> 'i' in x
True
>>> s.issubset(x)       #s是否为x的子集
True
>>> y
set(['i', 'e', 'm', 'd', 't'])
>>> x.union(y)        #交
set(['e', 'd', 'i', 'h', 'j', 'm', 't'])
>>> x.intersection(y)     #并
set(['i', 'e', 't'])
>>> x.difference(y)      #差
set(['h', 'j'])
>>> x.symmetric_difference(y) #对称差
set(['d', 'h', 'j', 'm'])
>>> s.update(x)        #更新s,加上x中的元素
>>> s
set(['e', 't', 'i', 'h', 'j'])
>>> s.add(1)         #增加元素
>>> s
set([1, 'e', 't', 'i', 'h', 'j'])
>>> s.remove(1)        #删除已有元素,如果没有会返回异常
>>> s
set(['e', 't', 'i', 'h', 'j'])
>>> s.remove(2)

Traceback (most recent call last):
 File "<pyshell#29>", line 1, in <module>
  s.remove(2)
KeyError: 2
>>> s.discard(2)        #如果存在元素,就删除;没有不报异常
>>> s
set(['e', 't', 'i', 'h', 'j'])
>>> s.clear()         #清除set
>>> s
set([])
>>> x
set(['i', 'h', 'j', 'e', 't'])
>>> x.pop()          #随机删除一元素
'i'
>>> x
set(['h', 'j', 'e', 't'])
>>> x.pop()
'h'

以上这篇浅谈Python 集合(set)类型的操作——并交差就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django REST framework 分页的实现代码

官方文档[这里] 用于分页的模块: Pagination Django REST framework 有内置 Pagination 模块,无需额外安装, 只需做简单的配置. 配置什么呢&...

打印出python 当前全局变量和入口参数的所有属性

def cndebug(obj=False): """ Author : Nemon Update : 2009.7.1 TO use : cndebug(obj) or cndebug...

Python数据分析之双色球基于线性回归算法预测下期中奖结果示例

Python数据分析之双色球基于线性回归算法预测下期中奖结果示例

本文实例讲述了Python数据分析之双色球基于线性回归算法预测下期中奖结果。分享给大家供大家参考,具体如下: 前面讲述了关于双色球的各种算法,这里将进行下期双色球号码的预测,想想有些小激...

Python实现DDos攻击实例详解

Python实现DDos攻击实例详解

SYN 泛洪攻击 SYN泛洪攻击是一种比较常用的Dos方式之一。通过发送大量伪造的 TCP 连接请求,使被攻击主机资源耗尽(通常是 CPU 满负荷或内存不足)的攻击方式 我们都知道建立...

对python中的try、except、finally 执行顺序详解

如下所示: def test1(): try: print('to do stuff') raise Exception('hehe') print('to r...