Python 基础学习 --- Note 07 --- 集合(set)

set 是无序的,而且元素不会重复

1. 创建集合

NB: Set could remove duplication automatically!

newSet = {1, 2, 3}

duplicatedSet = {'Saxon', 'GirlFriend', 'GirlFriend'}
print(duplicatedSet) # {'GirlFriend', 'Saxon'}
2. set basic operation
2.1 ‘in’ Operation
InOperationSet = {'Saxon', 'Girl', 'Boy'}
print('Girl' in InOperationSet) # True
2.2 Bi-operation

- : 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. set basic method
3.1 添加操作

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 删除操作

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'}

你可能感兴趣的:(python,python)