python 集合

一. 创建集合

创建集合使用`{}`或`set()`, 但是如果要创建空集合只能使用`set()`,因为`{}`用来创建空字典。

s1 = {10, 20, 30, 40, 50}
print(s1)  # {50, 20, 40, 10, 30}

s2 = {10, 30, 20, 10, 30, 40, 30, 50}  
print(s2)   # {50, 20, 40, 10, 30}

s3 = set('abcdefg')
print(s3)      # {'e', 'd', 'a', 'b', 'g', 'c', 'f'}

s4 = set()
print(type(s4))  # set

s5 = {}
print(type(s5))  # dict

注意:集合的元素无序不重复

二. 常见操作方法

1. add()

s1 = {10, 20}
s1.add(100)
s1.add(10)
print(s1)  # {100, 10, 20}

2. update() 新增一个序列

s1 = {10, 20}
# s1.update(100)  # 报错TypeError: 'int' object is not iterable
s1.update([100, 200])
s1.update('abc')
print(s1)

注意:参数必须为一个序列,否则报错

3. remove() 

s1 = {10, 20}

s1.remove(10)
print(s1)   # {20}

s1.remove(30)  # KeyError: 30
print(s1)

注意:一处不存在的数据会报错

4. discard(),删除集合中的指定数据,如果数据不存在也不会报错。

s1 = {10, 20}

s1.discard(10)
print(s1)   # {20}

s1.discard(10)
print(s1)   # {20}

5. pop() ,随机删除集合中的某个数据,并返回这个数据

s1 = {10, 20, 30, 40, 50}

del_num = s1.pop()
print(del_num)  # 50
print(s1)   # {20, 40, 10, 30}

s1 = set()
s1.pop()    # KeyError: 'pop from an empty set'

注意:空集合使用pop()会报错

6. 判断元素是否存在

- in:判断数据在集合序列
- not in:判断数据不在集合序列

s1 = {10, 20, 30, 40, 50}

print(10 in s1)     # True
print(10 not in s1)     # False

 

posted @ 2020-12-19 13:28  foreast  阅读(88)  评论(0编辑  收藏  举报