📅  最后修改于: 2023-12-03 14:46:04.033000             🧑  作者: Mango
In Python, a set is an unordered collection of unique elements. It is defined by enclosing a comma-separated list of elements in curly braces {}
. A set can contain various data types, such as integers, floats, strings, and other objects.
To create a set in Python, we can use the following syntax:
my_set = {1, 2, 3, 4, 5}
print(my_set)
Output:
{1, 2, 3, 4, 5}
Alternatively, we can create a set from a list using the set()
function:
my_list = [1, 2, 3, 4, 5]
my_set = set(my_list)
print(my_set)
Output:
{1, 2, 3, 4, 5}
We can add elements to a set using the add()
method:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
Output:
{1, 2, 3, 4}
Similarly, we can remove elements from a set using the remove()
method:
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)
Output:
{1, 3}
We can perform various operations on sets, such as union, intersection, and difference.
The union of two sets is the set of all elements that are in either set. We can use the |
or union()
method to perform union on two sets:
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a | set_b
print(union_set)
Output:
{1, 2, 3, 4, 5}
Alternatively, we can use the union()
method:
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a.union(set_b)
print(union_set)
Output:
{1, 2, 3, 4, 5}
The intersection of two sets is the set of all elements that are common to both sets. We can use the &
or intersection()
method to perform intersection on two sets:
set_a = {1, 2, 3}
set_b = {3, 4, 5}
intersection_set = set_a & set_b
print(intersection_set)
Output:
{3}
Alternatively, we can use the intersection()
method:
set_a = {1, 2, 3}
set_b = {3, 4, 5}
intersection_set = set_a.intersection(set_b)
print(intersection_set)
Output:
{3}
The difference of two sets is the set of all elements that are in the first set but not in the second set. We can use the -
or difference()
method to perform difference on two sets:
set_a = {1, 2, 3}
set_b = {3, 4, 5}
difference_set = set_a - set_b
print(difference_set)
Output:
{1, 2}
Alternatively, we can use the difference()
method:
set_a = {1, 2, 3}
set_b = {3, 4, 5}
difference_set = set_a.difference(set_b)
print(difference_set)
Output:
{1, 2}
Python sets are a powerful data structure that allows us to store and manipulate unique elements efficiently. With the various operations available, we can perform complex set operations with ease.