Python Data Structures: Sets


gather

Definition of a collection

A collection is a mutable, unordered container that cannot contain duplicate elements. You can think of a collection as a container of dictionary keys, and the elements in the collection are unique, unordered, and immutable.

Creation of collections

1. Use curly braces {} to create a non-empty collection, example as follows:

>>> s = {
    
    1,2,3,4,5}
>>> print(s)
{
    
    1,2,3,4,5}
>>> print(type(s))
<class 'set'>
>>> s = {
    
    [1, 2, 3, 1, 2]} # 列表为可变类型,不能当作集合的元素,会报错
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    s = {
    
    [1, 2, 3, 1, 2]}
TypeError: unhashable type: 'list'

Note: Empty curly braces can only be used to create dictionaries.

2. Use the set() function to convert other types to sets and remove duplicate values. Examples are as follows:

>>> s = set([1, 1, 2, 2, 3, 4, 8, 8]) # 将列表转化为集合
>>> print(s)
{
    
    1, 2, 3, 4, 8}
>>> print(type(s))
<class 'set'>

>>> s = set('python') # 将字符串转化为集合
>>> print(s)
{
    
    'n', 'h', 'p', 'y', 't', 'o'} # 集合是无序的,每次输出元素的位置都有可能不同
>>> print(type(s))
<class 'set'>

>>> s = set() # 使用set()函数创建空集合
>>> print(s)
set() # 空集合
>>> print(type(s))
<class 'set'>

The parameters of the set() function are iterable objects, such as strings, lists, tuples, etc. When there are no parameters, an empty set is created, and the empty set is represented by set() instead of {}. A collection is a mutable object, and elements in the collection can be added and deleted, but the collection is unordered and cannot be indexed and sliced ​​to obtain elements. At the same time, there is no key-value pair structure. , the elements in the collection cannot be obtained and modified.

Collection element addition

Collections provide some methods to add elements to them. The following are the common methods of adding:

1. The add() function adds a single element, the syntax is as follows:

set.add(obj)

parameter:

  • obj -- the element to be added

Return value: no return value

Add the element obj to the collection, and do nothing if the element already exists. An example is as follows:

>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.add('a') # 只能添加一个元素
{
    
    1, 2, 3, 4, 'a', 8}

2. The update() function adds multiple elements, the syntax is as follows:

set.update(seq)

parameter:

  • seq – elements to be added, parameters can be separated by commas, which can be lists, tuples, dictionaries, etc.

Return value: no return value

An example is as follows:

# 添加字符串
>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.update('python') 
>>> print(s)
{
    
    1, 2, 3, 4, 'y', 8, 'h', 't', 'o', 'p', 'n'}

# 添加列表
>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.update([7,9,12],[10,15,20]) 
>>> print(s)
{
    
    1, 2, 3, 4, 7, 8, 9, 10, 12, 15, 20}

# 添加元组
>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.update((7,9,12,10,15,20))
>>> print(s)
{
    
    1, 2, 3, 4, 7, 8, 9, 10, 12, 15, 20}

# 添加字典
>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.update({
    
    'name': 'lilei', 'age': 20, 'grade': 'three'}) # 添加字典的键
>>> print(s)
{
    
    1, 2, 3, 4, 'name', 8, 'grade', 'age'}

Collection element deletion

Collections provide several methods for removing elements:

1. The remove() function deletes, the syntax is as follows:

set.remove(x)

parameter:

  • x – The element to remove, an error will occur if the element does not exist.

Return value: No return value.

The sample code is as follows:

>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.remove(3) # 删除元素3
>>> print(s)
{
    
    1, 2, 4, 8}

>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.remove('a') # 删除集合内不存在的元素时报错
>>> print(s)
Traceback (most recent call last):
  File "test.py", line 2, in <module>
    print(s.remove('a'))
KeyError: 'a'

2. The discard() function is deleted, the syntax is as follows:

set.discard(x)

parameter:

  • x -- the element to remove, if the element does not exist, no error will occur.

Return value: No return value.

The sample code is as follows:

>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.discard(4) # 删除元素3
>>> print(s)
{
    
    1, 2, 3, 8}

>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.remove('a') # 删除集合内不存在的元素时不会报错
>>> print(s)
{
    
    1, 2, 3, 4, 8}

3. The pop() function randomly deletes an element in the collection, the syntax is as follows:

set.pop()

No parameters, the return value is randomly deleted elements, the collection is unordered, pop() will delete the first element on the left of the collection.

An example is as follows:

>>> s = {
    
    1, 2, 3, 4, 8}
>>> print(s.pop())
1 # 多次执行,被删除的值都不一样

4. The clear() function clears the collection, the syntax is as follows:

set.clear()

No parameters, no return value. An example is as follows:

>>> s = {
    
    1, 2, 3, 4, 8}
>>> s.clear() # 清空列表
>>> print(s) # 空集合
set()

collection of functions

Some methods are also provided in the collection, and some common methods are described below:

1. Copy the collection

The copy() method method is used to copy a collection, the syntax is as follows:

set.copy()

No parameters, return a copy of the value copy collection, example as follows:

>>> s = {
    
    1, 2, 3, 4, 8}
>>> print(s.copy()) 
{
    
    1, 2, 3, 4, 8}

2. Determine whether two sets contain the same elements

isdisjoint() is used to determine whether two sets contain the same elements, if not return True, otherwise return False, the syntax is as follows:

set.isdisjoint(set)

parameter:

  • set – required, the set to compare against

Return value: Boolean, True if not included, False otherwise.

An example is as follows:

>>> s1 = {
    
    1, 2, 3, 4, 8}
>>> s2 = {
    
    3, 4, 5, 7, 10}
>>> print(s1.isdisjoint(s2)) # 两个集合有共同的元素,返回False
False

set operations

Sets support various set operations in mathematical theory, which can be implemented not only through operation symbols, but also provide functions to implement set operations. The corresponding relationship is as follows:

method symbol describe
x.difference(y) x - y Difference of x and y
x.intersection(y) x & y intersection of x and y
x.union(y) x | y union of x and y
x.issubset(y) x < y x is a subset of y
x.issuperset (y) x > y x is a superset of y
x.symmetric_difference(y) x^y Symmetric difference between x and y

An example is as follows:

>>> s1 = {
    
    1, 2, 3, 4, 5}
>>> s2 = {
    
    4, 5, 6, 7, 8}

# 差集
>>> print(s1.difference(s2))
{
    
    1, 2, 3}
>>> print(s1 - s2)
{
    
    1, 2, 3}

# 交集
>>> print(s1.intersection(s2))
{
    
    4, 5}
>>> print(s1 & s2)
{
    
    4, 5}

# 并集
>>> print(s1.union(s2))
{
    
    1, 2, 3, 4, 5, 6, 7, 8}
>>> print(s1 | s2)
{
    
    1, 2, 3, 4, 5, 6, 7, 8}

# 子集
>>> print(s1.issubset(s2))
False
>>> print(s1 < s2)
False

# 超集
>>> print(s1.issuperset(s2))
False
>>> print(s1 > s2)
False

# 对称差
>>> print(s1.symmetric_difference(s2))
{
    
    1, 2, 3, 6, 7, 8}
>>> print(s1 ^ s2)
{
    
    1, 2, 3, 6, 7, 8}

Guess you like

Origin blog.csdn.net/shield911/article/details/124111146