Python learning ==> collection

gather:

        A set is also a data type, something like a list, which is unordered and non-repetitive, that is to say, there is no repeated data in the collection.

The role of the collection:

        1. It can remove duplicate data in a list without you needing to write judgment again

        2. You can do relationship testing. For example, there are two classes, one for performance testing and the other for interface testing. If you want to find students who have studied both performance and interface testing, you can use sets.

Define a collection:

list = [2,3,1,2,3,4] 
s1 = set()#Define an empty set
s2 = set('aaee1122')#The set will remove duplicate data
s3 = set(list)#Convert the list to A set
s4 = set([2,3,1,2,3,4])#This method and the above are to convert the list into a set
s5 = {1,2,1,4,2,5, 7}# This way directly defines a collection

Collection related operations:

s = {1,2,3,4,5,6,7} 
s.add(9) #Add element s.pop() #Randomly
delete an element
s.remove(7) #Specify which element to delete
s.update ({11,12,13}) #Add another set to the s set

Intersection:

s1 = set('aaee1122') 
s2 = {'1','2','1','4','2','5','7'}
print(s1 & s2)#Intersection
print( s1.intersection(s2))# Take the intersection
print(s1.isdisjoint(s2))# Determine whether list1 and list3 have intersection, if there is no intersection, return True, if there is intersection, return False

Union:

# Union: merge two sets together, deduplication 
s1 = set('aaee1122')
s2 = {'1','2','1','4','2','5',' 7'}
print(s1 | s2)#take the union
print(s1.union(s2))#take the union

Difference:

# Difference set: remove the elements that both sets have in the previous set and deduplicate 
s1 = set('aaee1122')
s2 = {'1','2','1','4','2', '5','7'}
print(s1 - s2)#take the difference
print(s1.difference(s2))#take the difference

Symmetric difference

# Symmetric difference set: remove both sets, then merge the two sets and deduplicate 
s1 = set('aaee1122')
s2 = {'1','2','1','4','2 ','5','7'}
print(s1 ^ s2)#take the symmetric difference
print(s1.symmetric_difference(s2))#take the symmetric difference

Small exercise:

# Check whether the password contains numbers, uppercase letters, lowercase letters and special symbols 
import string
num_set = set(string.digits)
upper_set = set(string.ascii_uppercase)
lower_set = set(string.ascii_lowercase)
pum_set = set(string.punctuation )
for i in range(5):
pwd = input('Please enter the password:').strip()
pwd_set = set(pwd)
if pwd_set & num_set and pwd_set & upper_set and pwd_set & lower_set and pwd_set & pum_set:
print(' The password input is valid')
break
else:
print('The password is invalid, the password must contain numbers, uppercase letters, lowercase letters and special characters')

Guess you like

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