How to use the set method in Python
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Detailed explanation of DeepSeekAPI access and call: Quick Start Guide This article will guide you in detail how to access and call DeepSeekAPI, helping you easily use powerful AI models. Step 1: Get the API key to access the DeepSeek official website and click on the "Open Platform" in the upper right corner. You will get a certain number of free tokens (used to measure API usage). In the menu on the left, click "APIKeys" and then click "Create APIkey". Name your APIkey (for example, "test") and copy the generated key right away. Be sure to save this key properly, as it will only be displayed once

A must-have for beginners and advanced programmers: Harness the power of Python programming. Python syntax is clear and concise, and indentation is used to represent code blocks. if-elif-else statements are used for conditional judgment. The Fibonacci sequence can be calculated through loops and variable assignments. Python provides powerful features, including data structures, modules, error handling, and object-oriented programming. Official documentation, tutorials, and online courses are available as learning resources. Master Python basics and functions to write efficient and maintainable code to solve programming problems.
