What is the purpose of the set() function in Python?
In Python, the set() function is used to create a collection that is unordered and contains no duplicate elements. It accepts an iterable object as a parameter and returns a set containing the unique elements from that iterable object.
Here are some common uses of the set() function:
- Remove duplicate elements: By passing an iterable object to the set() function, you can quickly remove any duplicate elements and obtain a set that only contains unique elements.
- Set operations: Various operations can be performed on sets using the set() function, such as union, intersection, and difference. By utilizing set operations, relationships between sets can be easily managed.
- Quick search: Due to the fact that the set is implemented based on a hash table, it has a fast search performance. As a result, by storing data in the set, it is possible to quickly determine if a particular element exists within the set.
- Mathematical operations: The set() function can also be combined with mathematical operators to perform operations such as finding the difference, union, intersection, and other mathematical operations between two sets.
Here are some examples:
# 创建一个包含唯一元素的集合
numbers = set([1, 2, 3, 3, 4, 5])
print(numbers) # 输出: {1, 2, 3, 4, 5}
# 集合操作
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2) # 并集
intersection_set = set1.intersection(set2) # 交集
difference_set = set1.difference(set2) # 差集
print(union_set) # 输出: {1, 2, 3, 4, 5}
print(intersection_set) # 输出: {3}
print(difference_set) # 输出: {1, 2}
# 判断元素是否存在于集合中
fruits = {'apple', 'banana', 'orange'}
print('apple' in fruits) # 输出: True
print('grape' in fruits) # 输出: False
# 数学运算
set3 = {1, 2, 3}
set4 = {3, 4, 5}
difference_set = set3 - set4 # 差集
union_set = set3 | set4 # 并集
intersection_set = set3 & set4 # 交集
print(difference_set) # 输出: {1, 2}
print(union_set) # 输出: {1, 2, 3, 4, 5}
print(intersection_set) # 输出: {3}
In conclusion, the set() function in Python is used to create, manipulate, and handle collection data structures, providing a convenient and efficient method.