Python basics 7 -- set, python7 -- Set
Set
The set in Python is an unordered, non-repeating element set. Basic functions include link testing and deduplication. The Set object also supports mathematical operations such as union, intersection, difference, and sysmmetric differencr.
Set supports x in set, len (set), and for x in set. As an unordered set, set does not record the subscript of the element.
Example:
1. Set Operations
1. Create a set
1 list1 = set('bigberg')2 list2 = set('smallberg')3 print(list1,type(list1))4 print(list2,type(list2))
2. add the element to be passed in to the set as a whole.
1 a = set('lion')2 a.add('rabbit')3 print(a)
3. Add update to the set to split the elements to be passed in and insert them into the set as an individual.
1 b = set('lion')2 b.update('rabbit')3 print(b)
4. remove a collection
1 a = set('lion')2 a.add('rabbit')3 print(a)4 5 a.remove('rabbit')6 print(a)
Ii. Set relationships
1. Union (deduplication)
1 a = {1, 2, 3, 3, 66} 2 B = {3, 4, 5, 6, 33} 3 4 print (a. union (B) # print (a | B)
{33, 2, 66, 3, 4, 1, 5, 6} # only one copy of the same part is retained.
2. Intersection
1 a = {1,2,3,4,33,66}2 b = {3,4,5,6,33}3 4 print(a.intersection(b))5 print(a & b)
{33, 3, 4}
{33, 3, 4}
3. difference set
1 a = {1,2,3,4,33,66}2 b = {3,4,5,6,33}3 4 print(a.difference(b))5 print(b.difference(a)) # print(b - a)
{1, 2, 66}
{5, 6}
4. Relative population
1 a = {1, 2, 3, 3, 66} 2 B = {3, 4, 5, 6, 33} 3 4 print (. effecric_difference (B) # Remove the same element 5 print (B. symmetric_difference ())
{1, 2, 5, 6, 66}
{2, 66, 5, 1, 6}
5. subset and parent set
1 a = {1, 2, 3, 3, 66} 2 B = {3, 4, 5, 6, 33} 3 4 print (. issubset (B) # subset 5 print (B. issuperset (a) # parent set
False
False