Intersection and union
Intersection
in Pythonintersection()Method is used to obtain the intersection of two collections. This method is a method of the set object, so it can only be used in the set object.
If you want to get intersections in other types of containers, you can use Python's built-in function set() to convert them to set objects. For example, you can use the following code to get the intersection of two lists:
1 | a = [1, 2, 3, 4] |
Here, we first use set() to convert the two lists a and b into set objects, and then use the intersection() method to get their intersection. Note that because sets are unordered, the order of elements in the resulting set may differ from the order in the original list.
In addition to set objects, Python's dictionary type also has a similar intersection() method for obtaining the intersection of the same keys of two dictionaries, but this is different from the above case.
Union
If you want to get the union of two containers, you can use Python's built-in functionset()Convert them to set objects and then useunion()Method to get their union. For example, the following code obtains the union of two lists:
1 | a = [1, 2, 3, 4] |
Here, we first useset()convert two listsaandbConvert tosetobject, then useunion()Method to get their union. Note that because sets are unordered, the order of elements in the resulting set may differ from the order in the original list.
Except for set objects, Python's dictionary types do not support union operations. If you need to perform a union operation on a dictionary, you can convert its keys or values into a set object and then perform the set operation. For example, the following code obtains the union of the keys of two dictionaries:
1 | a = {'x': 1, 'y': 2, 'z': 3} |
Here, we convert the keys of the two dictionaries into set objects, and then use the union() method to obtain their union.