Python set set - Python zero basics tutorial

Posted by gordsmash on Sat, 29 Jan 2022 09:38:10 +0100

catalogue

Zero basic Python learning route recommendation: Python learning directory >> Getting started with Python Basics

stay Python variables In addition to the integer int / floating point number float / Boolean bool mentioned in the previous article/ List list / Dictionary dict In addition, there is another type that we haven't introduced in detail. This variable type is set.

I Introduction to set set

Python set collection Braces {} are used to indicate that, unlike dict, the set set does not have a key / value pair. It mainly has the following two characteristics:

  • 1. Elements cannot be repeated;
  • 2.set does not record the addition order of elements, that is, it is disordered, which is similar to a dictionary;
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:Python set aggregate.py
@Time:2021/04/04 11:00
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!
 
"""

# Create an empty set
set_a = set()
# Print set
print(set_a)
# View type
print(type(set_a))
print("***"*20)

# Create a collection
set_b = {"Ape theory python",False}
print(type(set_b))
print(set_b)
print("***"*20)

# Create a dictionary
dict_b = {"name":"Ape theory python","url":"www.codersrc.com"}
print(type(dict_b))
print(dict_b)

'''
Output result:

set()
<class 'set'>
************************************************************
<class 'set'>
{False, 'Ape theory python'}
************************************************************
<class 'dict'>
{'name': 'Ape theory python', 'url': 'www.codersrc.com'}
'''

Code analysis: observe the above code. Although the dictionary dict and set are both composed of {}, note that the dictionary is composed of key / value pairs, and the set is composed of one data, and List list Similar elements!

II Set set common functions

  • add - adds an element to the set set;
  • Remove - delete the element. If the collection does not contain the deleted element, the remove() method will report a KeyError exception;
  • discard - delete the element. If the collection does not contain the deleted element, there will be no prompt or exception;
  • Clear - clear the blank set;
  • Copy - copy a set;
  • Difference - returns the difference set of multiple sets;
  • difference_update - remove the element in the set, which also exists in the specified set;
  • Intersection - returns the intersection of two sets without changing the set itself;
  • intersection_update - returns the intersection of sets, which will change the first set through intersection operation;
  • isdisjoint - judge whether two sets contain the same element. If not, return True; otherwise, return False;
  • issubset - judge whether the specified set is a subset of the method parameter set;
  • issuperset -- judge whether the parameter set of the method is a subset of the specified set;
  • pop - randomly remove elements;
  • symmetric_difference - remove the same elements in another specified set in the current set, and insert different elements in another specified set into the current set;
  • Union -- returns the union of two sets;
  • update - used to modify the current set. You can add a new element or set to the current set. If the added element already exists in the set, the element will only appear once, and repeated elements will be ignored;
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:Python set aggregate.py
@Time:2021/04/04 11:00
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!
 
"""

# Use curly braces to build a set set
c = {'Qiao Feng',"duan yu","Phyllostachys pubescens","Tianlong Babu","Legend of Shooting Heroes"}
# Add element
c.add("Tianshan grandma")
c.add(6)
print("c The number of elements in the collection is:" , len(c))
print(c)
# Delete the specified element
c.remove("Tianshan grandma")
print(c)
print("c The number of elements in the collection is:" , len(c))
print("***"*20)


# Determines whether the specified string is included
print("c Whether the collection contains'Qiao Feng'character string:" , ("Qiao Feng" in c)) # Output True
print("***"*20)

# Use the set() function (constructor) to create a set set
movies = set()
movies.add("Tianlong Babu")
movies.add("Legend of Shooting Heroes")
print("movies Elements of the collection:" , movies)
# The issubset() method determines whether it is a subset
print("movies Whether the collection is c Subset of?", movies.issubset(c)) # Output False

# The issuperset() method determines whether it is a parent set
# issubset and issuperset are actually the reverse judgment
print("c Is the collection fully contained books Assemble?", c.issuperset(movies)) # Output False
# Subtracting the elements in the books set from the c set does not change the c set itself
result1 = c - movies
print(result1)

# The difference() method also subtracts the set, which is exactly the same as the effect of performing the operation with -
result2 = c.difference(movies)
print(result2)

# Subtract the elements in the books set from the c set and change the c set itself
c.difference_update(movies)
print("c Elements of the collection:" , c)

# Delete all elements in the c set
c.clear()
print("c Elements of the collection:" , c)
print("***"*20)

# Directly create a collection containing elements
d = {"python object-oriented", 'python Basics', 'python Reptile'}
print("d Elements of the collection:" , d)

# The intersection() method also obtains the intersection of two sets, which is exactly the same as the effect of performing the operation with &
inter2 = d.intersection(movies)
print(inter2)
# Calculate the intersection of two sets and change the d set itself
d.intersection_update(movies)
print("d Elements of the collection:" , d)
print("***"*20)

# Wrap the range object into a set set
e = set(range(5))
f = set(range(3, 7))
print("e Elements of the collection:" , e)
print("f Elements of the collection:" , f)

# Calculate the union of two sets without changing the e set itself
un = e.union(f)
print('e and f Result of Union:', un)
# Calculate the union of two sets and change the e set itself
e.update(f)
print('e Elements of the collection:', e)

'''
Output result:

c The number of elements in the collection is: 7
{'Tianlong Babu', 6, 'Phyllostachys pubescens', 'Qiao Feng', 'duan yu', 'Tianshan grandma', 'Legend of Shooting Heroes'}
{'Tianlong Babu', 6, 'Phyllostachys pubescens', 'Qiao Feng', 'duan yu', 'Legend of Shooting Heroes'}
c The number of elements in the collection is: 6
************************************************************
c Whether the collection contains'Qiao Feng'character string: True
************************************************************
movies Elements of the collection: {'Tianlong Babu', 'Legend of Shooting Heroes'}
movies Whether the collection is c Subset of? True
c Is the collection fully contained books Assemble? True
{'Qiao Feng', 'duan yu', 6, 'Phyllostachys pubescens'}
{'Qiao Feng', 'duan yu', 6, 'Phyllostachys pubescens'}
c Elements of the collection: {6, 'Phyllostachys pubescens', 'Qiao Feng', 'duan yu'}
c Elements of the collection: set()
************************************************************
d Elements of the collection: {'python Reptile', 'python Basics', 'python object-oriented'}
set()
d Elements of the collection: set()
************************************************************
e Elements of the collection: {0, 1, 2, 3, 4}
f Elements of the collection: {3, 4, 5, 6}
e and f Result of Union: {0, 1, 2, 3, 4, 5, 6}
e Elements of the collection: {0, 1, 2, 3, 4, 5, 6}
'''

III Set set operator

  • < =: it is equivalent to calling the issubset() method to judge whether the previous set set is a subset of the subsequent set.
  • >=: it is equivalent to calling the issuperset() method to judge whether the previous set set is the parent set of the subsequent set.
  • –: it is equivalent to calling the difference() method and subtracting the elements of the subsequent set set from the previous set set.
  • &: it is equivalent to calling the intersection() method to obtain the intersection of two set s.
  • ^: the result of calculating the XOR of two sets is to subtract the elements of the intersection from the union of the two sets.
# !usr/bin/env python
# -*- coding:utf-8 _*-
"""
@Author:Ape programming
@Blog(Personal blog address): www.codersrc.com
@File:Python set aggregate.py
@Time:2021/04/04 11:00
@Motto:No small steps lead to thousands of miles. No small streams lead to rivers and seas. The brilliance of program life needs to be accumulated unremittingly!
 
"""

# Use curly braces to build a set set
c = {'Qiao Feng',"duan yu","Phyllostachys pubescens","Tianlong Babu","Legend of Shooting Heroes"}

# Use the set() function (constructor) to create a set set
movies = set()
movies.add("Tianlong Babu")
movies.add("Legend of Shooting Heroes")
print("movies Elements of the collection:" , movies)
# The issubset() method has the same effect as the < = operator
print("movies Whether the collection is c Subset of?", (movies <= c)) # Output False
print("***"*20)

e = set(range(5))
f = set(range(3, 7))
print("e Elements of the collection:" , e)
print("f Elements of the collection:" , f)
# Performs an XOR operation on two sets
xor = e ^ f
print('e and f implement xor Results:', xor)

# Directly create a collection containing elements
d = {"python object-oriented", 'python Basics', 'python Reptile'}
print("d Elements of the collection:" , d)
# Calculate the intersection of two sets without changing the d set itself
inter1 = d & movies
print(inter1)

'''
Output result:

movies Elements of the collection: {'Tianlong Babu', 'Legend of Shooting Heroes'}
movies Whether the collection is c Subset of? True
************************************************************
e Elements of the collection: {0, 1, 2, 3, 4}
f Elements of the collection: {3, 4, 5, 6}
e and f implement xor Results: {0, 1, 2, 5, 6}
d Elements of the collection: {'python Basics', 'python object-oriented', 'python Reptile'}
set()

'''

IV Guess you like it

  1. Conversion between Python Strings / lists / tuples / Dictionaries
  2. Python local and global variables
  3. Difference between Python type function and isinstance function
  4. Python is and = = difference
  5. Python variable and immutable data types
  6. Python shallow and deep copies
  7. Python recursive function
  8. Python sys module
  9. Python list
  10. Python tuple
  11. Python dictionary dict
  12. Python conditional derivation
  13. Python list derivation
  14. Python dictionary derivation
  15. Python function declarations and calls
  16. Python indefinite length parameter * argc/**kargcs

No reprint without permission: Ape programming ยป Python set collection

Topics: Python