内容简介:AThe following code block shows two sets, containing a collection of numbers and cities.Any immutable data type can be an element of a set (e.g. strings and integers). If you try to use a mutable data type inside a set, an exception (
10 things you should know about Sets in Python
1. What is a Python set?
A set is an unordered and mutable collection of unique elements. Sets are written with curly brackets ( {} ), being the elements separated by commas.
The following code block shows two sets, containing a collection of numbers and cities.
Any immutable data type can be an element of a set (e.g. strings and integers). If you try to use a mutable data type inside a set, an exception ( TypeError ) is raised, as shown below.
2. Create a set with set() constructor
Setscan also be defined with the built-in function set([iterable]) . This function takes as argument an iterable (i.e. any type of sequence, collection, or iterator), returning a set that contains unique items from the input (duplicated values are removed).
As shown above, the original order of the input items is not maintained, since sets are unordered containers.
We can also use the set() constructor without any input parameter. In this case, the constructor returns an empty set .
3. Add an element to a set
To add an element to a set , we use the set.add(element) method. This method modifies the set in-place, returning None .
As shown below, the .add() method does not add an element to the set if the element is already present, since sets cannot contain duplicated items.
Unlike with lists, we cannot insert an element at a given index, since sets are unordered containers, meaning elements have not a particular position inside a set .
4. Remove an element from a set
There are three ways of removing elements from a set:
- Using the set.remove(x) method
- Using the set.discard(x) method
- Using the set.pop() method
The remove method
The set.remove(x) method removes an element x from a set. This method modifies the set in-place, returning None . If the element x does not exist, an exception ( KeyError ) is raised.
The discard method
The set.discard(x) method removes an element x from a set if it is present. In comparison to the remove method , the discard method does not raise an exception ( KeyError ) if the element to be removed does not exist.
As shown above, the discard method modifies the set in-place, returning None .
The pop method
The set.pop() method removes and returns an arbitrary element from a set.
In comparison to lists , the pop method does not take any arguments. We can not specify the index we want to remove, since sets are an unordered collection of elements.
5. Mathematical operations: union, intersection, difference, and symmetric difference
We can use sets in Python to compute mathematical operations such as union , intersection , difference , and symmetric difference . These logical operations can be represented with a diagram called Venn diagram . Venn diagrams are widely used in mathematics, statistics, and computer science to visualize differences and similarities between sets. We can plot area-weighted two- and three-circle Venn diagrams with the third-party library matplotlib-venn.
Given two sets, one containing animals that are mammals and another one containing aquatic animals.
We can compute the aforementioned mathematical operations in the following manner.
Union
The union of two sets A and B is the set containing the elements that are in A , B , or both , and is denoted by A ∪ B .
The red shaded area of the Venn diagram represents the union of the sets mammals and aquatic.
To compute this operation with Python , we can use either the set.union(another set) method or the | operator.
As shown above, both return a new set containing all items from sets mammals and aquatic.
Intersection
The intersection of two sets A and B is the set containing the elements that are common to both sets and is denoted by A ∩ B .
The red shaded area of the Venn diagram represents the intersection of the sets mammals and aquatic.
In Python, we can compute the intersection of two sets using either the set.intersection(another set) method or the & operator.
As you can observe, the intersection method and the & operator return a new set, containing the items that exist in both sets without modifying them.
Difference
The difference of two sets A and B is the set of all elements of set A that are not contained in set B and is denoted by A-B .
The red shaded area of the Venn diagram represents the difference between mammals and aquatic (mammals-aquatic). This set contains the animals that are mammals but not aquatic.
We can also obtain the animals that are aquatic but not mammals, calculating the difference between aquatic and mammals.
To compute the difference between two sets in Python, we can use either the set.difference(another set) method (set-other set) or the ( – ) operator.
As you can observe, the sets mammals and aquatic are not modified in-place.
Symmetric difference
The symmetric difference of two sets A and B is the set of elements that are in either of the sets A and B , but not in both, and is denoted by A △ B.
The following Venn diagram represents the symmetric difference of the sets mammals and aquatic (red shaded area). This set contains the animals that are mammals and aquatic but not both.
In Python, we can find the symmetric difference of two sets using either the set.symmetric_difference(another set) method or the ^ operator as follows.
6. Subsets and supersets
A set A is a subset of a set B (A ⊆ B) or equivalently set B is a superset of set A (B ⊇ A), if all elements of set A are contained in set B .
The following Venn diagram represents two sets mammals and aquatic_mammals , being aquatic_mammals a subset of mammals .
To check whether set A is a subset/superset of set B , we can use the following methods:
- A.issubset(B) → This method returns True if all elements of set A are contained in set B.
- A.issuperset(B) → This method returns True if all elements of set B are contained in set A .
The following code block uses both methods to check if a set is a subset/superset of another set.
7. Disjoint
Two sets are disjoint if they have no elements in common. The following two sets mammals and reptiles are disjoint sets as their intersection is an empty set .
We can check if two sets are disjoint using the set.isdisjoint(another set) method. This method returns True if both sets have no elements in common. If they have, it returns False .
8. Check if an element exists in a set
To check whether an element exists in a set , we have to use a membership operator . Membership operators are used to test whether an element is present in a sequence (e.g. strings, lists, tuples, sets, or dictionaries). There are two membership operators, as explained below.
- in → Evaluates to True if the object on the left side is included in the object on the right side.
- not in → Evaluates to True if the object on the left side is not included in the object on the right side.
9. Find the length of a set
To determine how many elements the set contains, we can use the len() function. This function returns the number of items of an object. The input of the function can be not only a set, but also another type of sequence such as a string, dictionary, list, or tuple.
10. Alternative container: frozenset
A frozenset object is a set that, once created, cannot be changed. We create a frozenset in Python using the frozenset([iterable]) constructor, providing an iterable as input.
Since frozensets are immutable, they do not accept the methods that modify sets in-place such as add , pop , or remove . As shown below, trying to add an element to a frozenset raises an exception ( AttributeError ).
Unlike sets, frozensets can be used as keys in a dictionary or as elements of another set.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
C++面向对象程序设计
萨维奇 (Walter Savitch) / 周靖 / 清华大学出版社 / 2003-12 / 59.0
《C++面向对象程序设计》具备良好的编排体系,适合打算涉足编程领域的读者阅读,尤其适合大一学生。它最大的特色是Savitch教授最受欢迎的写作风格,这一风格非常适合初学者,能迅速引导他们开始编程实践。《C++面向对象程序设计》包括全面的习题、项目、编程提示、编程示例、编程陷阱以及有用的小结,以帮助初学者更清楚地了解C++。一起来看看 《C++面向对象程序设计》 这本书的介绍吧!