python3 set of common operations

Set of common operations

Work is often set to use a data type; also more convenient to use, the following operation is common in python set;

Relationship test:

operating method Operators
Intersection intersection() &
Union union() |
Child Collection issubset() <
Superset issuperset() >
Difference set difference() -
Symmetric difference symmetric_difference() ^
#Return True if two set have a null intersection
set_1 = {1,2,3,4}
set_2 = {2,3}
set_2.isdisjoint(set_1) # False

Set operations

example: set_1 = {2, 6, 8}

Add to:

set_1.add(10) #Add an element to a set. This has no effect if the element is already present.
set_1.update([1, 3, 5]) #Update a set with the union of itself and others.

delete

set_1.pop() #Remove and return an arbitary set element. Raises KeyError if the set is empty.
set_1.remove(2) #Remove an element from a set; it must be a member. if not, raise KetError
set_1.discard(888) #Remove an element from a set if it is a member. if not, do nothing

note

update () method pass nested data types what will happen?

If hereset_1.update([7,8,(9,10)]) , the results will complain it ?

Here you will pass set_1, get {7,8,(9,10)}

Well, if passed it is [7,8,[9,10]]what will happen?

Of course, such a nested format is passed being given (TypeError: unhashable type: 'list') for the following reasons:

The type of error, non-removable type, also known as non-hash. This anomaly occurs because the use of set () process, set () is not passed in the hash element, while the inner nested list due to decomposition, to be treated as an element in the set, it must be hashed , we know that the definition of the collection, the element is not in the sET repetitive, disordered, which elements must be a hash, i.e., immutable (int, str, tuple, bool )
hashable there are elements: int, float, str, tuple
not have hash elements: list, set, dict, then the type can not be nested inside three
Why is not the list of hash, and tuples are hashable :

  • Because the list is variable, the value of the element can be changed at any therein.
  • Hash elements can not decide whether to use the hash value index
  • Without using hash list index of the element, its nature storage element requires no hash; hash values ​​using the set index.

Guess you like

Origin www.cnblogs.com/janeyu/p/11099182.html