浅谈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设计】。

相关文章

python使用urllib2实现发送带cookie的请求

本文实例讲述了python使用urllib2实现发送带cookie的请求。分享给大家供大家参考。具体实现方法如下: import urllib2 opener = urllib2.b...

Python图算法实例分析

本文实例讲述了Python图算法。分享给大家供大家参考,具体如下: #encoding=utf-8 import networkx,heapq,sys from matplotlib...

详解Python:面向对象编程

面向过程的程序设计把计算机程序视为一系列的命令集合,即一组函数的顺序执行。为了简化程序设计,面向过程把函数继续切分为子函数,即把大块函数通过切割成小块函数来降低系统的复杂度 python...

Python进程间通信Queue消息队列用法分析

本文实例讲述了Python进程间通信Queue消息队列用法。分享给大家供大家参考,具体如下: 进程间通信-Queue Process之间有时需要通信,操作系统提供了很多机制来实现进程间的...

OpenCV python sklearn随机超参数搜索的实现

本文介绍了OpenCV python sklearn随机超参数搜索的实现,分享给大家,具体如下: """ 房价预测数据集 使用sklearn执行超参数搜索 """ import ma...