search
HomeBackend DevelopmentPython TutorialHow to use the set method in Python
How to use the set method in PythonMay 11, 2023 pm 02:31 PM
pythonset

1. Preface

In Python, set is a set data type, representing an unordered and non-repeating set. The set() method can be used to create an empty collection or to convert other iterable objects into a collection. Unlike other Python data types, a set does not have an index and its elements cannot be accessed by index, but there are methods that can be used to manipulate and access the elements in the set. Create an empty collection using the set() method

2. Detailed explanation of the commonly used set() method

1.add(): Add an element to the set collection

# add()语法如下:
set.add(elmnt)

# 案例如下:
set1 = {1,2,3}
set1.add(4)
print(set1)

# 输出结果如下
{1, 2, 3, 4}

2.clear(): Remove all elements from the set collection

# clear()语法如下:
set.clear()
# 案例如下:
set1 = {1, 2, 3}
set1.clear()
print(set1)
# 输出结果如下:
set()

3.copy(): Used to copy a collection, use copy( ) method creates a complete copy of the original collection, and operations on the copied collection will not affect the original collection.

# 语法如下:
new_set = old_set.copy()
# 案列如下:
set1 = {1, 2, 3}
set2 = set1.copy()
set2.add(4)
print(set1)
print(set2)
# 输出结果如下:
{1, 2, 3}
{1, 2, 3, 4}
# 首先,我们创建了一个原始集合,然后使用copy方法创建了一个新集合,并在新集合中添加了一个元素4,
# 最后,我们打印了原始集合和复制出的新集合,可以看到两个集合互不影响。

4.difference(): This method is used to return the difference set of the set, that is, the returned set elements are included in the first set, but not in the second set ( method parameters).

# 语法如下:
set1.difference(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.difference(set2))
# 输出结果如下:
{1}

5.difference_update(): method is used to remove elements that exist in both collections

difference_update() method and difference() method The difference is that the difference() method returns a new collection with the same elements removed, while the difference_update() method directly removes elements from the original collection without returning a value.

# 语法如下:
set1.difference_update(set2)
# 案例如下:
set1 = {1, 2, 3, 4, 5}
set2 = {2, 3, 4}
set1.difference_update(set2)
print(set1)
# 输出结果如下
{1, 5}

6.discard() method syntax: The discard() method is used to remove specified collection elements.

This method is different from the remove() method because the remove() method will cause an error when removing a non-existent element, while the discard() method will not.

# 语法如下:
set.discard(value)
# 案例如下
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1.discard(2), set2.discard(3)
print(set1, set2)
# 输出结果如下:
{1, 3} {2, 4}
# 删除不存在元素,不会引发任何异常
set1.discard(4)
print(set1)
# 输出结果如下
{1, 2, 3}

7. The intersection() method is used to return elements contained in two or more sets, that is, the intersection.

# 语法如下:
set1.intersection(set2, set3, ...)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = set1.intersection(set2)
print(set3)
# 输出结果如下:
{2, 3}

8. The intersection_update() method is used to obtain overlapping elements in two or more sets, that is, to calculate the intersection.

The intersection_update() method is different from the intersection() method because the intersection() method returns a new set, while the intersection_update() method removes non-overlapping elements on the original set.

# 语法如下:
set1.intersection_update(set2, set3, ...)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1.intersection_update(set2)
print(set1)
# 输出结果如下:
{2, 3}

9.isdisjoint() method is used to determine whether two sets contain the same elements. If not, it returns True, otherwise it returns False.

# 语法如下:
set1.isdisjoint(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {4, 5, 6}
print(set1.isdisjoint(set2))
print(set3.isdisjoint(set1))
# 输出如果如下:
False
True

10.issubset() method is used to determine whether a set is a subset of another set. If all elements of one set are contained in another set, return True if so, otherwise return False

# 语法如下:
set1.issubset(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {1, 2, 3, 4}
print(set1.issubset(set2))
print(set1.issubset(set3))
# 输出结果如下:
False
True

11.issuperset() method is used to determine whether one set is another set A superset of a set. If a set contains all elements of another set, the set is a superset of the other set, and the issuperset() method returns True; otherwise, it returns False.

# 语法如下:
set1.issuperset(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {1, 2, 3, 4}
print(set1.issuperset(set2))
print(set3.issuperset(set1))
# 输出结果如下:
False
True

12.pop() method is used to randomly remove an element and return the value of the element.

# 语法如下:
set.pop()
# 案例如下:
# 随机移除一个元素:
set1 = {1, 2, 3, 4}
set1.pop()
print(set1)
# 结果如下:
{2, 3, 4}
# 输出返回值:
set1 = {1, 2, 3, 4}
print(set1.pop())
# 结果如下:
1

13.remove() method is used to remove specified elements from the collection.

This method is different from the discard() method because the remove() method will cause an error when removing a non-existent element, while the discard() method will not.

# 语法如下:
set.remove(item)
# 案例如下:
set1 = {1, 2, 3, 4}
set1.remove(4)
print(set1)
# 输出结果如下:
{1, 2, 3}

14. The symmetric_difference() method returns a set of non-duplicate elements in the two sets, that is, it will remove the elements that exist in both sets, that is, it will return the elements that are different from each other in the two sets. Collection of elements.

# 语法如下:
set1.symmetric_difference(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.symmetric_difference(set2))
# 输出结果如下:
{1, 4}

15. The symmetric_difference_update() method removes the same elements from the current collection in another specified collection, and inserts different elements from another specified collection into the current collection.

# 语法如下:
set1.symmetric_difference_update(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4, 5}
set1.symmetric_difference_update(set2)
print(set1)
# 输出结果如下:
{1, 4, 5}

16. The union() method returns the union of two sets, which contains the elements of all sets. Duplicate elements will only appear once.

# 语法如下:
set1.union(set2)
# 案例如下:
# 合并两个集合,重复元素只会出现一次:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
print(set1.union(set2))
# 输出结果如下:
{1, 2, 3, 4}
# 合并多个集合:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set3 = {3, 4, 5, 6, 7}
print(set1.union(set2, set3))
# 输出结果如下:
{1, 2, 3, 4, 5, 6, 7}

17.update(): method is used to modify the current collection. You can add new elements or collections to the current collection. If the added element already exists in the collection, then the Elements will appear only once, and duplicates will be ignored.

# 语法如下:
set1.update(set2)
# 案例如下:
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set1.update(set2)
print(set1)
# 结果如下:
{1, 2, 3, 4}

3. Summary

1. Create an empty collection

It is very simple to create an empty collection using the set() method. Simply call the set() method to create an empty set object.

# 例子:
set_data = set()
print(set_data)
# 输出结果如下:
set()

2. Convert iterable objects to sets

The set() method can also convert other iterable objects (such as lists, tuples, and strings) into sets.

# 案例:
list1 = [1, 2, 3, 4, 5]
set1 = set(list1)
print(set1)
tuple1 = (1, 2, 3, 4, 5)
set2 = set(tuple1)
print(set2)
str1 = "Hello, world!"
set3 = set(str1)
print(set3)
# 输出结果如下:
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
{'d', 'H', 'o', ',', 'l', 'e', '!', 'r', 'w', ' '}

3. Other uses of the set() method

Split the string into individual characters and store them in a set.

# 例子:
str2 = "Python"
set4 = set(str2)
print(set4)
# 输出结果:
{'h', 't', 'o', 'n', 'P', 'y'}

4. Conclusion

Collection objects have many built-in methods for adding, deleting, merging, comparing, and manipulating elements in the collection. The following are some common methods of set objects:

  • add(): used to add a single element to the set.

  • clear(): Used to clear all elements in the collection.

  • copy(): Used to create a copy of the collection.

  • difference(): Used to return the difference between two sets.

  • difference_update(): Used to delete elements in a collection that are the same as another collection.

  • discard(): Used to delete the specified element in the collection.

  • intersection(): Used to return the intersection of two sets.

  • intersection_update(): Used to retain the same elements in a collection as another collection.

  • isdisjoint(): Used to determine whether two sets have no common elements.

  • issubset(): Used to determine whether a set is a subset of another set.

  • issuperset(): Used to determine whether a set is a superset of another set.

  • pop(): Used to randomly remove an element.

  • remove(): Used to remove the specified element from the collection.

  • symmetric_difference(): Used to return the symmetric difference of two sets.

  • symmetric_difference_update(): Used to retain non-common elements in the set and delete common elements.

  • union(): Used to return the union of two sets.

  • update(): Used to add elements from one collection to another collection.

These methods can be used by calling the method name on the collection object and providing the necessary parameters. For example, use the add() method to add a single element to a collection, and use the update() method to add elements from one collection to another.

The above is the detailed content of How to use the set method in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.