current position:Home>Python notes (8): basic operations of collections

Python notes (8): basic operations of collections

2022-01-30 10:41:18 A bowl week

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

Hello everyone , I am a A bowl week , One doesn't want to be drunk ( Internal volume ) The front end of the . If you are lucky enough to get your favor , I'm very lucky ~

aggregate

Python There is basically no difference between sets in and sets in Mathematics , Is chaotic , That is, those that cannot be accessed by index , There can be no duplicate elements in the collection .

Create set

stay Python Use curly braces to create collections in {} In a literal way , Or use set() To create a collection . Use {} Must contain at least one element , Creating an empty collection cannot use {}, This creates an empty dictionary , You should use set() To create a collection .

#  Use the literal method to create a collection 
set1 = {"Hello", "World"}
print(type(set1), set1)  # <class 'set'> {'World', 'Hello'}
# print(set1[1]) # TypeError: 'set' object does not support indexing

#  Use set() The way to create 
set2 = set("hello")  # {'l', 'o', 'h', 'e'} The collection will remove duplicate elements , namely "l"
print(set2)

#  Create an empty set 
set3 = {}
set4 = set()
print(type(set3), type(set4))  # <class 'dict'> Dictionaries  <class 'set'>

list1 = [1, 2, 3, 4, 3, 5, 1, 3]
#  Convert list to set 
set6 = set(list1)
print(type(set6), set6)  # <class 'set'> {1, 2, 3, 4, 5}

#  Use the generated column to generate a list 
set5 = {num for num in range(20) if num % 3 == 0}
print(set5)  # {0, 3, 6, 9, 12, 15, 18}

#  Traversal cycle 
for ch in set5:
    print(ch)
 Copy code 

Be careful : The elements in the collection are immutable types , Such as integers 、 floating-point 、 character string 、 Tuples etc. , In other words, variable types cannot be elements of tuples , The collection itself is also a mutable type , So a set cannot be an element in a set .

The operation of sets

The collection data type has too many operators , Including member operations 、 Intersection operation 、 Union operation 、 Subtraction operation 、 Comparison operations ( Equality 、 A subset of 、 Superset ) etc. .

Members of the operation

You can operate through members in and not in Check whether the element is in the collection , Sample code ↓

set1 = {" Hello ", "Python", " This is ", " aggregate ", "set"}
print("Python" in set1)  # True
print(" Hello! " in set1)  # False
print("set" not in set1)  # False
print("list" not in set1)  # True
 Copy code 

Intersection, union and subtraction

Python A set in is the same as a set in Mathematics , You can intersect 、 Combine 、 Subtraction and so on , And it can be operated by operator and method call .

The sample code is as follows :

set1 = {1, 2, 3, 4, 5, 6, 7}
set2 = {2, 4, 6, 8, 10}

#  intersection ( We both have )
#  Method 1 :  Use  &  Operator 
print(set1 & set2)                # {2, 4, 6}
#  Method 2 :  Use intersection Method 
print(set1.intersection(set2))    # {2, 4, 6}

#  Combine ( We put together )
#  Method 1 :  Use  |  Operator 
print(set1 | set2)         # {1, 2, 3, 4, 5, 6, 7, 8, 10}
#  Method 2 :  Use union Method 
print(set1.union(set2))    # {1, 2, 3, 4, 5, 6, 7, 8, 10}

#  Difference set ( I don't want what you have )
#  Method 1 :  Use  -  Operator 
print(set1 - set2)              # {1, 3, 5, 7}
#  Method 2 :  Use difference Method 
print(set1.difference(set2))    # {1, 3, 5, 7}

#  Symmetry difference ( We don't want yours or mine , Just be specific )
#  Method 1 :  Use  ^  Operator 
print(set1 ^ set2)                        # {1, 3, 5, 7, 8, 10}
#  Method 2 :  Use symmetric_difference Method 
print(set1.symmetric_difference(set2))    # {1, 3, 5, 7, 8, 10}
#  Method 3 :  The symmetry difference is equivalent to subtracting the intersection from the union of two sets 
print((set1 | set2) - (set1 & set2))      # {1, 3, 5, 7, 8, 10}
 Copy code 

Intersection of sets 、 Combine 、 The difference set operation can also be combined with the assignment operation to form a composite operation , The sample code is as follows :

set1 = {1, 3, 5, 7}
set2 = {2, 4, 6}
#  take set1 and set2 Find the union set and assign it to set1
#  It can also be done through set1.update(set2) To achieve 
set1 |= set2  # set1 = set1 | set2
print(set1)    # {1, 2, 3, 4, 5, 6, 7}
set3 = {3, 6, 9}
#  take set1 and set3 Find the intersection and assign it to set1
#  It can also be done through set1.intersection_update(set3) To achieve 
set1 &= set3  # set1 = set1 & set3
print(set1)    # {3, 6}
 Copy code 

Comparison operations

Two sets can be used == and != Make an equality judgment , If the elements in two sets are exactly the same , that == The result of the comparison is True, Otherwise, it would be False;!= On the contrary .

If the collection A All elements of are also collections B The elements of , It's called A yes B Subset ,B yes A Superset ; If the collection A And not equal to the set B, It's called A yes B True child of . The operators for judging subsets and supersets are < and >. Sample code ↓

set1 = {1, 3, 5}
set2 = {1, 2, 3, 4, 5}
set3 = set2
# < Operator represents the true subset ,<= Operators represent subsets 
print(set1 < set2, set1 <= set2)    # True True
print(set2 < set3, set2 <= set3)    # False True
#  adopt issubset Method can also make subset judgment 
print(set1.issubset(set2))      # True
print(set2.issubset(set2))      # True
# issubset Methods and <= Operators are equivalent 

#  In turn, you can use issuperset or > Operator to determine the superset 
print(set2.issuperset(set1))    # True
print(set2 > set1)              # True
 Copy code 

The way to assemble

The collection is of variable column type , The elements of a collection can be modified by the method of collection type , Sample code ↓

#  Create an empty set 
set1 = set()

#  adopt add() Method to add elements to the collection 
set1.add(1)
set1.add(2)
print(set1)  # {1, 2}

#  adopt update() Add elements to the collection 
set1.update({1, 2, 3, 4, 5})
print(set1)  # {1, 2, 3, 4, 5}  Element already exists in the collection , This element will only appear once 

#  adopt discard() Method deletes the specified element 
set1.discard(4)
set1.discard(2)
set1.discard(22)  #  There are no errors in the collection 
print(set1)  # {1, 3, 5}

#  adopt remove() Method deletes the specified element 
# set1.remove(6) # KeyError: 6, Use remove() Method to delete the specified element, do the member operation first, and there will be no error 
if 6 in set1:
    set1.remove(6)

# pop Method can randomly delete an element from the collection and return the element 
print(set1.pop())  # 1  What is excluded this time is 1

# clear Method can empty the entire collection 
set1.clear()
print(type(set1))  # <class 'set'>
print(set1)    # set()

#  adopt isdisjoint() Method to determine whether there are duplicate elements in two sets , There is a return False No return Ture
set2 = {"Hello", "World"}
set3 = {"Hello", " A bowl week "}
set4 = {"Hi", "Python"}
print(set2.isdisjoint(set3))  # False
print(set2.isdisjoint(set4))  # True
 Copy code 

Immutable set

Python There is also a collection of immutable types in , Name is frozenset, The difference between sets is the same as that between lists and tuples . Except that you can't add or delete elements ,frozenset In other ways with set It's basically the same . Sample code ↓

set1 = frozenset({1, 3, 5, 7})
set2 = frozenset(range(1, 6))
print(set1 & set2)    # frozenset({1, 3, 5})
print(set1 | set2)    # frozenset({1, 2, 3, 4, 5, 7})
print(set1 - set2)    # frozenset({7})
print(set1 < set2)    # False
 Copy code 

copyright notice
author[A bowl week],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301041141900.html

Random recommended