Python3 set (set) (15th), python3 set
A set is a sequence of unordered, non-repeating elements.
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.
Similar to dict, set is also a set of keys, but does not store values. Because keys cannot be repeated, there are no duplicate keys in the set.
You can use braces {} or the set () function to create a set. Note: To create an empty set, you must use set () instead of {}, because {} is used to create an empty dictionary.
Creation format:
1 parame = {value01, value02,...} 2 or 3 set (value)
Example:
1 #! /Usr/bin/python3 2 3 student = {'Tom ', 'Jim', 'Mary ', 'Tom', 'jack ', 'Rose '} 4 5 print (student) # output set, repeated elements are automatically removed 6 7 # member Test 8 if ('Rose' in student ): 9 print ('Rose in collection ') 10 else: 11 print ('Rose not in collection ') 12 13 14 # set operation 15 a = set ('abracadaba') 16 B = set ('acazam') 17 18 print () 19 20 print (a-B) # a and B's difference set 21 22 print (a | B) # a and B's Union set 23 24 print (a & B) # intersection of a and B 25 26 print (a ^ B) # elements that do not exist simultaneously in a and B
Output result of the above instance:
1 {'Mary ', 'Jim', 'Rose ', 'jack', 'Tom'} 2 Rose in the Set 3 {'B', 'A ', 'C', 'R', 'D'} 4 {'B', 'D', 'R'} 5 {'l', 'R', 'A ', 'C', 'z', 'M', 'B', 'D'} 6 {'A', 'C'} 7 {'l', 'R ', 'Z', 'M', 'B', 'D '}
Common Operations:
1 s = set ([3, 5, 9, 10]) # create a value set 2 3 t = set ("Hello ") # create a set of unique characters 4 5 6 a = t | s # The Union of t and s 7 8 B = t & s # The intersection of t and s 9 10 c = t- s # evaluate the difference set (the item is in t, but not in s) 11 12 d = t ^ s # symmetric difference set (items in t or s, but not both) 13 14 15 16 basic operations: 17 18 t. add ('x') # add a 19 20 s. update ([, 42]) # add more than 21 22 23 24 in s. Use remove () to delete one item: 25 26 t. remove ('H') 27 28 29 len (s) 30 set length 31 32 x in s 33 test x is a member of s 34 35 x not in s 36 test x is not a member of s 37 38 s. issubset (t) 39 s <= t 40 test whether every element in s is 41 42 s in t. issuperset (t) 43 s> = t 44 test whether every element in t is 45 46 s in s. union (t) 47 s | t 48 returns a new set containing s and each element in t 49 50 s. intersection (t) 51 s & t 52 returns a new set containing the public elements 53 54 s in s and t. difference (t) 55 s-t 56 returns a new set containing elements in s but not in t 57 58 s. until ric_difference (t) 59 s ^ t 60 returns a new set containing the non-repeating elements of s and t 61 62 s. copy () 63 returns a shortest copy of set "s"