A collection (set) is a sequence of unordered, non-repeating elements.
Its main function is as follows:
- Go to the weight, turn a list into a set, and then automatically go heavy.
- Relationship test, test the intersection of two sets of data, difference set, and the relationship between the set
Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set
You can create a collection using the curly braces {} or the set () function, note: Creating an empty collection must be set () instead of {}, because {} is used to create an empty dictionary.
To create a format:
1 parame = {value01,value02,...} 2 or 3 set (value)
Cases:
1#!/usr/bin/python32 3 student = {'Tom','Jim','Mary','Tom','Jack','Rose'} 4 5Print(student)#output set, duplicate elements are automatically removed6 7#member Test8if('Rose' inchstudent):9Print('Rose in the collection')10Else :11Print('Rose is not in the collection.')12 13 14#set can perform set operationsA = set ('Abracadabra')b = Set ('Alacazam')17 18Print(a)19 20Print(A-B)#the difference between A and B21 22Print(A | b)#the set of A and B23 24Print(A & B)#intersection of A and B25 26Print(a ^ b)#elements in A and b that do not exist at the same timeCopy Code
The result of the above example output:
1 {'Mary','Jim','Rose','Jack','Tom'}2Rose in the collection3 {'b','a','C','R','D'}4 {'b','D','R'}5 {'L','R','a','C','Z','m','b','D'}4 9'a','C'}9 5'L','R','Z','m','b','D'}
Common operations:
s = set ([3,5,9,10])#create a collection of values2 3 T = Set ("Hello")#Create a collection of unique characters4 5 6 a = T | S#the set of T and S7 8 B = t & S#intersection of T and S9 C = T–s#differential Set (items in T, but not in s)D = t ^ s#symmetric difference sets (items in t or S, but not both)13 14 15 16Basic Operation:T.add ('x')#Add an itemS.update ([10,37,42])#adding multiple items in S21 22 23 24use Remove () to delete an item:T.remove ('H') 27 28 29Len (s)30the length of the setXinchs33Test if X is a member of SX not inchs36Test if X is not a member of S37 38S.issubset (t)<= sT40Test if every element in S is in t41 42S.issuperset (t)S >=T44tests if every element in T is in S45 46s.union (t)s |T48returns a new set containing each element in S and T49 50s.intersection (t)Wuyi S &T52returns a new set containing the common elements in s and T53 54s.difference (t)S-T56returns a new set containing elements in s but not in T57 58s.symmetric_difference (t)s ^T60returns a new set containing elements that are not duplicates in S and T61 62s.copy ()63 returns a shallow copy of the set "s"
Reprinted from: https://www.cnblogs.com/jiyimeng/p/python11152.html
Python3---collection