set 是无序的,而且元素不会重复
NB: Set could remove duplication automatically!
newSet = {1, 2, 3}
duplicatedSet = {'Saxon', 'GirlFriend', 'GirlFriend'}
print(duplicatedSet) # {'GirlFriend', 'Saxon'}
InOperationSet = {'Saxon', 'Girl', 'Boy'}
print('Girl' in InOperationSet) # True
- : set difference operation
set1 = set('aabbccdd') # set1: {'a', 'b', 'c', 'd'}
set2 = set('aaccddee') # set2: {'a', 'e', 'c', 'd'}
print(set1 - set2) # {'b'}
| : set union operation
set1 = set('aabbccdd') # set1: {'a', 'b', 'c', 'd'}
set2 = set('aaccddee') # set2: {'a', 'e', 'c', 'd'}
print(set1 | set2) # {'a', 'b', 'c', 'd', 'e'}
&: set intersect operation
set1 = set('aabbccdd') # set1: {'a', 'b', 'c', 'd'}
set2 = set('aaccddee') # set2: {'a', 'e', 'c', 'd'}
print(set1 & set2) # {'a', 'c', 'd'}
^: set singular operation
set1 = set('aabbccdd') # set1: {'a', 'b', 'c', 'd'}
set2 = set('aaccddee') # set2: {'a', 'e', 'c', 'd'}
print(set1 ^ set2) # {'b', 'e'}
3.1.1 set.add(element)
添加一个元素
addSet = {'Saxon', 'Male', 18}
addSet.add('Love')
print(addSet) # {18, 'Male', 'Saxon', 'Love'}
3.1.2 set.update(...list)
添加多个元素
updateSet = {'Saxon', 'Male', 18}
updateSet.update(['Love', 'Perfect'])
print(updateSet) # 注意无视顺序 {'Saxon', 'Male', 18, 'Love', 'Perfect'}
' 可以一次性添加多个列表中的元素 '
updateSet.update(['Programmer'], ['GPA4.0']) # {'Saxon', 'Male', 18, 'Love', 'Perfect', 'Programmer', 'GPA4.0'}
print(updateSet)
3.2.1 set.remove(element)
NB: 当元素不存在时会报错
removeSet = {'Saxon', 18, 'Male', 'Growup'}
removeSet.remove(18)
print(removeSet) # {'Male', 'Saxon', 'Growup'}
3.2.2 set.discard(element)
NB: 当元素不存在时不会报错
discardSet = {'Saxon', 18, 'Male'}
discardSet.discard(19) # 没有报错
print(discardSet) # {'Saxon', 18, 'Male'}
3.2.3 set.pop()
NB: set 集合的 pop 方法会对集合进行无序的排列,然后将这个无序排列集合的左面第一个元素进行删除
popSet = {'a', 'b', 'c'}
print(popSet) # {'c', 'a', 'b'}
popSet.pop()
print(popSet) # {'a', 'b'}