What is a collection? For indefinitely or a group of dizzy students can have a look.
First don't want to say too many conceptual things, lest again faint!
Take a look at the example I wrote below and naturally know what a collection is and how to apply it after reading it.
#变量a是一个集合类型a = set () print (type (a)) #定义一个列表 and deposit many duplicate numbers dt = [12,9,2,8,4,9,2,7,4,5,6,11,5,7,5,7,9,8,7,2]for i in DT: #遍历列表 A.add (i) #将列表中的每一个元素添加进集合 # Print collection, found, automatically remove the duplicate number of print (a) #5存在于集合中吗? Print (5 in a) #遍历集合for item in A:print (item) #将集合转化成列表set_list = List (a) print (set_list) print (Type (set_list))
Well, the collection also involves a few of the following:
and set:
It takes two sets as arguments and returns a new collection containing all the elements that exist in any of the two collections, with the Union () method, which is: "|"
Intersection:
It receives the 2nd set as a parameter, and returns only those elements that exist at the same time in the two collection, the intersection method implementation, the operator is: "&"
Subtraction
It tells us which is the remaining element, which is a collection of objects stored in or present in this set or another collection, but not at the same time in two collections.
Symmetric_difference method Implementation, operator is: "-"
Continue to see examples
A = {1,2,3,4,5}b = {6,2,3,7} #求a和b的并集, after removing the numbers that are common in both sets of data, generate a new set of print (A.union (b)) #求a和b的交集 that do not have duplicate numbers, and extract the numbers from both sets of data. and generate a new collection, let us know which numbers in both sets of data exist in the two sets of data print (A.intersection (b)) #求a和b的差集, after the two sets of data are not in the extraction of numbers, the generation of a new set of print (A.symmetric _difference (b)) #注意: Their results depend on who is the caller, who is the parameter, the above 3 example, the A set is the caller, the B collection is the parameter #a all the numbers in the collection are present in the B collection, then returns True, A is the caller, B is the parameter print ( A.issubset (b)) #b集合作为参数, all elements in the B collection are present in the a set, returning Trueprint (A.issuperset (b)) #想要知道全部只存在于a集合而不存在于b集合的元素print ( A.difference (b)) #结果是1, 4,5# whereas print (B.difference (a)) #结果是6和7
Summarize:
By testing the description, the collection can be used to manipulate another collection, and the collection is more than just a container
Then, the scenario is generally as follows:
1, to two different data, if you want to quickly combine to do analysis, then use the set
2, so fast combination of purpose is generally why? , like to know which of the two data are duplicates and which are different
So:
Collections are a great way to compare data
python--Collection is a great way to compare data