[Deep Learning] Python and NumPy Tutorial Series (V): Python Container: 3. Detailed explanation of Set (initialization, accessing elements, common operations, common functions)

Table of contents

I. Introduction

2. Experimental environment

3. Python Containers (Containers)

0. Introduction to containers

1. List

2. Tuple

3. Set

1. Initialization

2. Access collection elements

3. Common operations

a. Add a single element (add)

b. Add multiple elements (update)

c. Delete

d. Determine whether the element exists in the set

4. Commonly used functions

a. Intersection

b. Union

c. Difference set

d. Symmetric difference set

e. Summary


I. Introduction

        Python is a high-level programming language created by Guido van Rossum in 1991. It is known for its concise, easy-to-read syntax, powerful functionality, and wide range of applications. Python has a rich standard library and third-party libraries that can be used to develop various types of applications, including web development, data analysis, artificial intelligence, scientific computing, automation scripts, etc.

        Python itself is a great general-purpose programming language and, with the help of some popular libraries (numpy, scipy, matplotlib), becomes a powerful environment for scientific computing. This series will introduce the Python programming language and methods of using Python for scientific computing, mainly including the following content:

  • Python: basic data types, containers (lists, tuples, sets, dictionaries), functions, classes
  • Numpy: arrays, array indexing, data types, array math, broadcasting
  • Matplotlib: plots, subplots, images
  • IPython: Creating notebooks, typical workflow

2. Experimental environment

        Python 3.7

        Run the following command to check the Python version

 python --version 

3. Python Containers (Containers)

0. Introduction to containers

        Containers in Python are objects used to store and organize data. Common containers include List, Tuple, Set and Dictionary.

  • Lists are ordered mutable containers that can contain elements of different types and are created using square brackets ([]).
my_list = [1, 2, 3, 'a', 'b', 'c']
  • Tuples are ordered immutable containers that can also contain elements of different types and are created using parentheses (()).
my_tuple = (1, 2, 3, 'a', 'b', 'c')
  • A set is an unordered and non-duplicate container used to store unique elements. It is created using curly brackets ({}) or the set() function.
my_set = {1, 2, 3, 'a', 'b', 'c'}
  •  A dictionary is an unordered container of key-value pairs used to store values ​​with unique keys. It is created using curly braces ({}) or the dict() function.
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}

        These containers provide different methods and operations for storing, accessing and processing data. You can choose a suitable container type according to your specific needs.

1. List

[Deep Learning] Python and NumPy Series Tutorials (3): Python Container: 1. Detailed explanation of List (initialization, indexing, slicing, updating, deletion, common functions, unpacking, traversal)_QomolangmaH's blog-CSDN blog https: icon-default.png?t=N7T8// blog.csdn.net/m0_63834988/article/details/132768246?spm=1001.2014.3001.5501

2. Tuple

[Deep Learning] Python and NumPy Series Tutorials (4): Python Container: 2. Detailed explanation of tuples (initialization, indexing and slicing, tuple characteristics, common operations, unpacking, traversal)_QomolangmaH's blog-CSDN blog https: icon-default.png?t=N7T8/ /blog.csdn.net/m0_63834988/article/details/132777307?spm=1001.2014.3001.5501

3. Set

        Set is a common data structure. A set is an unordered container containing unique elements. Its characteristic is that it does not allow repeated elements, and can perform various set operations such as intersection, union, and difference. Sets do not support direct unpacking operations because sets are unordered and the position of elements cannot be determined by indexing.

1. Initialization

Collections can be created         using braces {}or functions.set()

my_set = {1, 2, 3}  # 使用大括号创建集合
my_set = set([1, 2, 3])  # 使用set()函数创建集合

2. Access collection elements

        Unlike lists and tuples, the elements in a collection are unordered and therefore cannot be accessed by index. Additionally, the elements in the collection must be hashable (i.e., immutable) because the collection itself is implemented based on a hash table. We can access elements using loops or converting the collection to other indexable data structures:

a. Use a loop to traverse the elements in the collection

my_set = {1, 2, 3, 4, 5}
for element in my_set:
    print(element)

This will output every element in the collection.

b. Convert to other data structures

        Convert the collection to a List or Tuple and access elements by index.

my_set = {1, 2, 3, 4, 5}

my_list = list(my_set)
print(my_list[0])  # 访问第一个元素

my_tuple = tuple(my_set)
print(my_tuple[2])  # 访问第三个元素

3. Common operations

a. Add a single element (add)

my_set.add(5)  # 添加单个元素

b. Add multiple elements (update)

my_set.update([6, 7, 8])  # 添加多个元素

c. Delete

        You can remove an element from a collection using remove()a method that raises KeyErroran exception if the element does not exist, or discard()a method that does not raise an exception if the element does not exist.

my_set.remove(3)      # 移除指定元素,如果不存在会引发KeyError异常
my_set.discard(4)     # 移除指定元素,如果不存在不会引发异常

d. Determine whether the element exists in the set

my_set = {1, 2, 3}  
element = 3
if element in my_set:
    print("元素存在于集合中")

4. Commonly used functions

        These operations can be performed using corresponding methods (such as intersection(), union(), difference(), symmetric_difference()) or operators (such as &, |, -, ^).

a. Intersection

        The intersection of sets is a new set that contains all elements that are present in two or more sets. Intersection can be calculated using the intersection operator ( &) or intersection()methods.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# 使用交集运算符
intersection = set1 & set2
print(intersection)

# 使用intersection()方法
intersection = set1.intersection(set2)
print(intersection)

The output is:

{3, 4}

b. Union

        The union of sets is a new set that contains all unique elements that belong to two or more sets. The union can be calculated using the union operator ( |) or method.union()

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# 使用并集运算符
union = set1 | set2
print(union)

# 使用union()方法
union = set1.union(set2)
print(union)

The output is:

{1, 2, 3, 4, 5}

c. Difference set

        The difference set of a set is a new set obtained by removing all elements belonging to another set from one set. The difference can be calculated using the difference operator ( -) or difference()method.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}

# 使用差集运算符
difference = set1 - set2
print(difference)

# 使用difference()方法
difference = set1.difference(set2)
print(difference)

The output is:

{1, 2}

d. Symmetric difference set

        A symmetric difference set of sets is a new set that contains unique elements that belong to both sets, but does not contain elements that are present in both sets. Symmetric differences can be calculated using the symmetric difference operator ( ^) or methods.symmetric_difference()

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# 使用对称差集运算符
symmetric_difference = set1 ^ set2
print(symmetric_difference)

# 使用symmetric_difference()方法
symmetric_difference = set1.symmetric_difference(set2)
print(symmetric_difference)

The output is:

{1, 2, 4, 5}

e. Summary

set1 = {1, 2, 3}
set2 = {3, 4, 5}

intersection1 = set1.intersection(set2)  # 交集
intersection2 = set1 & set2  # 交集

union1 = set1.union(set2)  # 并集
union2 = set1 | set2  # 并集

difference1 = set1.difference(set2)  # 差集
difference2 = set1 - set2  # 差集

symmetric_difference1 = set1.symmetric_difference(set2)  # 对称差集
symmetric_difference2 = set1 ^ set2  # 对称差集

Guess you like

Origin blog.csdn.net/m0_63834988/article/details/132779181