Python set set() add delete, intersection, union, set operation details

In Python set is a collection type of basic data types, which has two types: mutable set (set()) and immutable set (frozenset) . The operations of creating a set, adding a set, deleting a set, intersection, union, and difference are all very practical methods.
1. Create

In [1]:set('boy')
Out[1]: {'b', 'o', 'y'}

2. Collection addition and deletion
There are two common methods for adding python collections, namely add and update.
Collection add method: It is to add the elements to be passed in as a whole to the collection, and the insertion position is random, for example:

a=set('boy')
a.add('python')
a
Out[4]: {'b', 'o', 'python', 'y'}

3. Collection update method: It splits the elements to be passed in and passes them into the collection as individuals, for example:

a.update('my')
a
Out[6]: {'b', 'm', 'o', 'python', 'y'}

4. Collection delete operation method: remove

a.remove('python')
a
Out[8]: {'b', 'm', 'o', 'y'}

5. Intersection, collection (union), and difference of sets

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # 这里演示的是去重功能
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # 快速判断元素是否在集合内
True
>>> 'crabgrass' in basket
False

>>> # 下面展示两个集合间的运算.
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # 集合a中包含元素
{'r', 'd', 'b'}
>>> a | b                              # 集合a或b中包含的所有元素
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # 集合a和b中都包含了的元素
{'a', 'c'}
>>> a ^ b                              # 不同时包含于a和b的元素
{'r', 'd', 'b', 'm', 'z', 'l'

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324738904&siteId=291194637