First, the collection
Collections are unordered, non-repeatable collections of data. The elements inside the collection are non-hashed (immutable types) (elements, strings, numbers), but the collection itself is not hashed (so the collection does not have a dictionary key).
Main functions:
1. Go to the weight, turn a list into a set, and automatically go heavy.
2. Relationship test, test the intersection of two sets of data, difference set, and the relationship between the set.
1. Create a Collection
Set = {' A ', ' B ', ' C '}
Set = Set ({' A ', ' B ', ' C '})
Print (set)
2. Increase
Set.add (' ASD ') #增加
Set.update (' ASD ') #迭代加, an additional
3. Delete
Set.remove (' Alex ') #按元素删
Set.pop () #随机删除
Set.clear () #清空, the return value is set ()
Del set #删除字集
4. Check
Print (set)
5. Other operations
Set1 = {1,2,3,4,5}
Set2 = {4,5,6,7,8}
1) Intersection (SET1 and Set2 same element)
Print (Set1 & Set2)
Print (Set1.intersection (Set2))
2) and set (all elements of Set1 and Set2)
Print (Set1 | set2)
Print (Set1.union (Set2))
3) Difference set (there are no elements in the Set1 in the Set2)
Print (Set1-set2)
Print (Set1.difference (Set2))
4) Inverse intersection (SET1 and Set2 different elements)
Print (set1 ^ set2)
Print (Set1.symmetric_difference (Set2))
5) subset (Set1 in element Set2)
Print (Set1 < Set2)
Print (Set1.issubset (Set2))
6) Superset (SE1 all elements in Set2)
Print (Set2 > Set1)
Print (Set2.issuperset (SET1))
7) Immutable collection (Frozenset)
Set1 = {4,5}
Set2 = Frozenset (Set1)
Print (Set2,type (Set2))
Results: Frozenset ({4, 5}) <class ' Frozenset ' >
Second, in-depth copy
1. Assignment operation
L1 = [1,2,3,[' Alex ', ' Barry ']
L2 = L1
L1[0] = 111
Print (L1 is L2)
L1 and L2 point to the same memory address, so changes to L1,L2 are also changed.
2. Shallow copy
L1 = [1,2,3,[' Alex ', ' Barry ']
L2 = L1.copy ()
L1.append (' as ')
Print (L1 is L2) #结尾为False, L1 plus content, L1 is not equal to L2
L1 = [1,2,3,[' Alex ', ' Barry ']
L2 = L1.copy ()
L1[3].append (' sa ')
Print (L1[3] is l2[3]) results in the list transformation in the TRUE,L1 L2 list is also transformed.
Conclusion: Shallow copy the first layer is a different memory address, but the second layer or deeper is the same memory address.
3. Deep copy
To solve the shallow copy problem, use the Copy module.
Import Copy
L1 = [1,2,3,[' Alex ', ' Barry ']
L2 = copy.deepcopy (L1)
L1[3].append (' sa ')
Print (L1 is L2)
So the memory address of L1 and L2 is completely different.
Python Seventh Day