Collection
Unordered mutable sequence, where elements in a collection are not allowed to repeat, that is, each element is unique
The elements in the collection are sorted in ascending order
1 #Create a collection2>>aset = Set ([0,2,4,5,7,2,3,5,9, 0])3>>Print(Aset)4{0, 2, 3, 4, 5, 7, 9}5 #add elements, insert collections sequentially6>>aset.add (6)7>>Print(Aset)8{0, 2, 3, 4, 5, 6, 7, 9}9 Ten #Delete Element One>>Aset.pop () A>>Print(Aset) -{2, 3, 4, 5, 6, 7, 9} - #Remove Deletes the specified element the>>aset.remove (2) -{3, 4, 5, 6, 7, 9} - #Clear Clear ->>aset.clear () +>>Print(Aset) -Set ()
Collection operations
1>>aset = {1,2,3,5,7}2>>bset = {4,5,6,7}3 #and set4>>aset |bset5{1, 2, 3, 4, 5, 6, 7}6 #intersection7>>aset &bset8{5, 7}9>>aset.intersection (bset)Ten{5, 7} One #Difference Set A>>aset.difference (bset) -{1, 2, 3} - #symmetry Difference the>>aset.symmetric_difference (bset) -{1, 2, 3, 4, 6} - #test whether a subset ->>x={1,2} +>>X.issubset (aset) - True +>>X.issubset (bset) AFalse
Because the elements in the collection are unique, you can use a collection to extract a single element from a sequence, or to generate a random sequence that is not duplicated
1>> fromRandomImportRandint2>> fromCollectionsImportCounter3>>LISTR = [Randint (0,100) forIinchRange (40)]4>>numfreq =Counter (LISTR)5>>Print(numfreq)6Counter ({3:1,74:2,87:1,913:1,Ten17:1, One19:1, A23:1, -26:1, -44:1, the50:1, -52:1, -53:1, -54:1, +55:1, -60:1, +62:1, A68:1, at73:1, -77:1}) - #a random number contains 2 4 ->>norepeat =Set (LISTR) ->>Print(norepeat) -3, 4, 7, 13, 17, 19, 23, 26, 44, 50, 52,
53, 54, 55, 60, 62, 68, 73, 77} in #there is only one 4 in the generated collection
Python basic data Type--collection