Python - Set

Feature:

  • No order
  • No repetition
  • Element Immutable
  • Set itself is mutable

Create a Set

# method 1
set1 = {1,2,3,4}
# method 2: 
set2 = set([1,2,3,4]) # pass an iterable element

Immutable Set

set1 = set([1,2,3,4])
immutable_set = frozenset(set1)

Relational Operation

in: check whether one element in one set
not in: check wether one element no in one set
==: check whether two sets are equal in values
!=: check whether two sets are not equal in values
|: Union
&: Intersection
-: Difference
^: XOR-Select elements not in common in two sets

Set Builtin Medthod

add(): add one element to a set
clear(): remove all elements from a set
difference(): equal to - operation
difference_update(): equal to - and assignment operation
remove(): remove one element(with exceptions)
discard(): remove one element (without exceptions)
intersection(): equal to & operation
isdisjoint():true if two sets have no intersection
issuperset(): true if one element is the superset of this set
issubset(): true if one element is the subset of this set
symmetric_difference(): equal to ^ operation
union(): equal to | operation
update(): add an iterable collection of elements to a set

猜你喜欢

转载自blog.csdn.net/ZenG_xiangt/article/details/81479429
今日推荐