首页 > 编程 > Python > 正文

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

2019-11-25 16:40:50
字体:
来源:转载
供稿:网友

阅读目录

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

介绍

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'])>>> yset(['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 - xset(['m', 'd'])>>> x ^ y  #对称差:x和y的交集减去并集set(['d', 'h', 'j', 'm'])

函数操作

 

>>> xset(['i', 'h', 'j', 'e', 't'])>>> s = set("hi")>>> sset(['i', 'h'])>>> len(x)          #长度>>> 'i' in xTrue>>> s.issubset(x)       #s是否为x的子集True>>> yset(['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中的元素>>> sset(['e', 't', 'i', 'h', 'j'])>>> s.add(1)         #增加元素>>> sset([1, 'e', 't', 'i', 'h', 'j'])>>> s.remove(1)        #删除已有元素,如果没有会返回异常>>> sset(['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)        #如果存在元素,就删除;没有不报异常>>> sset(['e', 't', 'i', 'h', 'j'])>>> s.clear()         #清除set>>> sset([])>>> xset(['i', 'h', 'j', 'e', 't'])>>> x.pop()          #随机删除一元素'i'>>> xset(['h', 'j', 'e', 't'])>>> x.pop()'h'

以上这篇浅谈Python 集合(set)类型的操作――并交差就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表