The path to python practice (six sets) and the path to python practice
Due to work, learning has been stuck for a long time and lags behind a lot. Really, learning persistence is very important. There are too many temptations around us, and any difficulties may be the reason for giving up. Keep yourself walking, even if the step is small, as long as you go, there is hope. Send it to yourself.
Set
A set is an unordered, non-repeating data combination. Its main functions are as follows:
- Deduplication: automatically removes duplicates when a list is changed to a set.
- Test the relationship between the intersection, difference set, and union of the two groups of data.
Change List to set
list_1 = [1,4,5,7,3,6,7,9]
liset_1 = set(list_1)
print(list_1,type(list_1))
>>>
[1, 4, 5, 7, 3, 6, 7, 9] <class 'LIST'>
Process finished with exit cod
Intersection
List_1 = [,]
Liset_1 = set (list_1)
List_2 = set ([, 4])
Print (list_1, list_2)
List_1.intersection (list_2)
Print (list_1.intersection (list_2 ))
>>>
[4, 6]
Union
List_1 = [,]
Liset_1 = set (list_1)
List_2 = set ([, 4])
Print (list_1.union (list_2 ))
>>>
[,]
Difference set
List_1 = [,]
Liset_1 = set (list_1)
List_2 = set ([, 4])
Print (list_1.difference (list_2 ))
>>>
[1, 3, 5, 9, 7]
Subset
List_1 = [,]
Liset_1 = set (list_1)
List_2 = set ([, 4])
Print (list_1.issubset (list_2 ))
>>>
False
Parent set
List_1 = [,]
Liset_1 = set (list_1)
List_2 = set ([, 4])
Print (list_1.issuperset (list_2 ))
>>>
False
Symmetric Difference set
List_1 = [,]
Liset_1 = set (list_1)
List_2 = set ([, 4])
Print (list_1.issubset (list_2 ))
>>>
[0, 1, 2, 66, 3, 5, 7, 9, 22]
No Intersection
Print ("-----------")
List_3 = set ([1, 3, 7])
List_4 = set ([5, 6, 8])
Print (list_3.isdisjoint (list_4 ))
>>>
True
Of course, the operation can also be completed with symbols:
S = set ([,]) # create a numerical set
T = set ("Hello") # create a set of unique characters
A = t | s # The Union of t and s
B = t & s # intersection of t and s
C = t-s # calculate the difference set (the item is in t, but not in s)
D = t ^ s # symmetric difference set (the items are in t or s, but not both)
Basic operations:
T. add ('x') # add an item
S. update ([10, 37, 42]) # add multiple
You can use remove () to delete an item:
T. remove ('H ')
Len (s)
Set length
X in s
Test whether x is a member of s.
X not in s
Test whether x is not a member of s
S. issubset (t)
S <= t
Test whether every element in s is in t
S. issuperset (t)
S> = t
Test whether every element in t is in s
S. union (t)
S | t
Returns a new set containing every element of s and t.
S. intersection (t)
S & t
Returns a new set containing the public elements in s and t.
S. difference (t)
S-t
Returns a new set that contains elements in s but not in t.
S. symmetric_difference (t)
S ^ t
Returns a new set that contains no repeated elements in s and t.
S. copy ()
Returns a shortest copy of set "s ".