Python Introductory Tutorial | Python3 Collection (Set)

Python3 collection (Set)

A collection (set) is an unordered sequence of elements that do not repeat.

The elements in the set will not be repeated, and common set operations such as intersection, union, and difference can be performed.

Sets can be created using curly braces { } with elements separated by commas, or using the set() function.
Create format :

parame = {
    
    value01,value02,...}
或者
set(value)

Here is a simple example:

set1 = {
    
    1, 2, 3, 4}            # 直接使用大括号创建集合
set2 = set([4, 5, 6, 7])      # 使用 set() 函数从列表创建集合

Note : To create an empty collection, you must use set() instead of { }, because { } is used to create an empty dictionary.
More example demonstrations:

>>> 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中包含而集合b中不包含的元素
{
    
    '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'}

Like list comprehensions, sets also support set comprehensions:

>>> a = {
    
    x for x in 'abracadabra' if x not in 'abc'}
>>> a
{
    
    'r', 'd'}

Basic operations on collections

1. Add elements

The syntax format is as follows:

s.add( x )

Adds the element x to the set s, or does nothing if the element already exists.

>>> thisset = set(("Google", "Tarzan", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{
    
    'Taobao', 'Facebook', 'Google', 'Tarzan'}

There is another method, which can also add elements, and the parameters can be lists, tuples, dictionaries, etc. The syntax format is as follows:

s.update( x )

There can be multiple x, separated by commas.

>>> thisset = set(("Google", "Tarzan", "Taobao"))
>>> thisset.update({
    
    1,3})
>>> print(thisset)
{
    
    1, 3, 'Google', 'Taobao', 'Tarzan'}
>>> thisset.update([1,4],[5,6])  
>>> print(thisset)
{
    
    1, 3, 4, 5, 6, 'Google', 'Taobao', 'Tarzan'}
>>>

2. Remove elements

The syntax format is as follows:

s.remove( x )

Removes the element x from the set s, or throws an error if the element does not exist.

>>> thisset = set(("Google", "Tarzan", "Taobao"))
>>> thisset.remove("Taobao")
>>> print(thisset)
{
    
    'Google', 'Tarzan'}
>>> thisset.remove("Facebook")   # 不存在会发生错误
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Facebook'
>>>

In addition, there is a method that also removes the element in the collection, and if the element does not exist, no error will occur. The format is as follows:

s.discard( x )

code example

>>> thisset = set(("Google", "Tarzan", "Taobao"))
>>> thisset.discard("Facebook")  # 不存在不会发生错误
>>> print(thisset)
{
    
    'Taobao', 'Google', 'Tarzan'}

We can also set to randomly delete an element in the collection, the syntax format is as follows:

s.pop() 

Example of script mode:

thisset = set(("Google", "Tarzan", "Taobao", "Facebook"))
x = thisset.pop()

print("随机删除元素:"+x)

Output result:

Tarzan

The test results are different for multiple executions.

The pop method of the set collection will arrange the collection unordered, and then delete the first element on the left of the unordered collection.

3. Calculate the number of set elements

The syntax format is as follows:

len(s)

In interactive mode, count the number of elements in the set s.

>>> thisset = set(("Google", "Tarzan", "Taobao"))
>>> len(thisset)
3

4. Empty collection

The syntax format is as follows:

s.clear()

Empty collection s.
Example in interactive mode:

>>> thisset = set(("Google", "Tarzan", "Taobao"))
>>> thisset.clear()
>>> print(thisset)
set()

5. Determine whether the element exists in the collection

The syntax format is as follows:

x in s

Determine whether the element x is in the set s, return True if it exists, and return False if it does not exist.
Example in interactive mode:

>>> thisset = set(("Google", "Tarzan", "Taobao"))
>>> "Tarzan" in thisset
True
>>> "Facebook" in thisset
False
>>>

Complete list of collection built-in methods

method describe
add() add elements to the set
clear() remove all elements from the set
copy() copy a collection
difference() Returns the difference of multiple sets
difference_update() Removes an element from a collection that also exists in the specified collection.
discard() removes the specified element from the collection
intersection() Returns the intersection of sets
intersection_update() Returns the intersection of sets.
isdisjoint() Determine whether the two collections contain the same element, if not return True, otherwise return False.
issubset() Determines whether the specified collection is a subset of the method's parameter collection.
superset() Determine whether the parameter set of the method is a subset of the specified set
pop() Randomly remove elements
remove() remove specified element
symmetric_difference() Returns a collection of unique elements from both collections.
symmetric_difference_update() Removes the same elements in the current collection that are in another specified collection, and inserts the different elements in the other specified collection into the current collection.
union() Returns the union of two collections
update() add elements to the collection

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/132661423