Home  >  Article  >  Backend Development  >  Python set type operations and intersection

Python set type operations and intersection

高洛峰
高洛峰Original
2017-03-01 13:56:041709browse

Reading Contents

•Introduction
•Basic Operations
•Function Operations

Introduction

Python's set is an unordered set of non-repeating elements. Its basic functions include relationship testing and elimination of duplicate elements. Set objects also support union, intersection, difference, symmetric difference, etc.

sets supports x in set, len(set), and for x in set. As an unordered collection, sets do not record element positions or insertion points. Therefore, sets do not support indexing, slicing, or other sequence-like operations.

Basic operations

##

>>> 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'])

Function operations

>>> 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 "", line 1, in 
  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'

The above article briefly discusses the operation and intersection of Python set (set) types. This is all the content shared by the editor. I hope it can To give you a reference, I also hope that everyone will support the PHP Chinese website.

For more Python set (set) type operations and related articles, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn