Python Data Structure 简明教程
Python - Sets
在数学上,集合是按任何特定顺序排列的项的集合。Python 集合类似于该数学定义,附加以下条件。
Mathematically a set is a collection of items not in any particular order. A Python set is similar to this mathematical definition with below additional conditions.
-
The elements in the set cannot be duplicates.
-
The elements in the set are immutable(cannot be modified) but the set as a whole is mutable.
-
There is no index attached to any element in a python set. So they do not support any indexing or slicing operation.
Set Operations
Python 中的集合通常用于数学运算,如并集、交集、差集和补集等。我们可以创建一个集合,访问其元素并进行如下所示的数学运算。
The sets in python are typically used for mathematical operations like union, intersection, difference and complement etc. We can create a set, access it’s elements and carry out these mathematical operations as shown below.
Creating a set
使用 set() 函数或将所有元素放在一对大括号中来创建集合。
A set is created by using the set() function or placing all the elements within a pair of curly braces.
Accessing Values in a Set
我们无法在集合中访问单个值。我们只能像上面所示那样一起访问所有元素。但是我们也可以通过遍历集合来获取单个元素的列表。
We cannot access individual values in a set. We can only access all the elements together as shown above. But we can also get a list of individual elements by looping through the set.
Adding Items to a Set
我们可以通过使用 add() 方法将元素添加到集合中。再次如所讨论的,没有特定索引附加到新添加的元素。
We can add elements to a set by using add() method. Again as discussed there is no specific index attached to the newly added element.
Removing Item from a Set
我们可以通过使用 discard() 方法从集合中删除元素。再次如所讨论的,没有特定索引附加到新添加的元素。
We can remove elements from a set by using discard() method. Again as discussed there is no specific index attached to the newly added element.
Union of Sets
对两个集合的并集运算产生一个新集合,其中包含两个集合的所有不同元素。在下面的示例中,元素“星期三”存在于两个集合中。
The union operation on two sets produces a new set containing all the distinct elements from both the sets. In the below example the element “Wed” is present in both the sets.
Intersection of Sets
对两个集合的交集运算产生一个新集合,其中仅包含两个集合的公共元素。在下面的示例中,元素“星期三”存在于两个集合中。
The intersection operation on two sets produces a new set containing only the common elements from both the sets. In the below example the element “Wed” is present in both the sets.
Difference of Sets
对两个集合的差集运算产生一个新集合,其中仅包含第一个集合的元素,而不包含第二个集合中的任何元素。在下面的示例中,元素“星期三”存在于两个集合中,因此不会出现在结果集中。
The difference operation on two sets produces a new set containing only the elements from the first set and none from the second set. In the below example the element “Wed” is present in both the sets so it will not be found in the result set.
Compare Sets
我们可以检查给定的集合是否是另一个集合的子集或超集。结果根据集合中存在的元素确定为 True 或 False。
We can check if a given set is a subset or superset of another set. The result is True or False depending on the elements present in the sets.