Python:集合
集合set
1.由不同元素组成的集合,集合是一组无序排列的,集合中的元素必须是不可变的
- 定义集合
第一种:
jh = {1,2,3,4}
print(type(jh),jh)
运行结果:
<class 'set'> {1, 2, 3, 4}
Process finished with exit code 0
第二种:
jh = set('hello')
print(type(jh),jh)
运行结果:
<class 'set'> {'e', 'o', 'h', 'l'}
Process finished with exit code 0
- 添加元素
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
jh = {1,2,3,4}
jh.add("nihao")
print(jh)
{1, 2, 3, 4, 'nihao'}
Process finished with exit code 0
- 删除
*.clear 清除集合
*.pop 随机删除
jh = {1,2,3,4}
jh.pop()
print(jh)
运行结果:
{2, 3, 4}
Process finished with exit code 0
*.remove 删除指定元素(如果指定的元素不在,会报错)
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
jh = {1,2,3,4}
jh.remove(4)
print(jh)
运行结果:
{1, 2, 3}
Process finished with exit code 0
*.discard 删除指定元素(如果指定元素不在,不会报错)
- 交集 &
math = {'xm','xh','xg'}
english ={'xm','xh'}
print(math.intersection(english))
运行结果:
{'xh', 'xm'}
Process finished with exit code 0
- 并集 |
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
math = {'xm','xh','xg','xx'}
english ={'xm','xh','dm','john'}
print(math.union(english))
运行结果:
{'xg', 'dm', 'john', 'xm', 'xx', 'xh'}
Process finished with exit code 0
- 差集(也可以两个集合做减法)
math = {'xm','xh','xg','xx'}
english ={'xm','xh','dm','john'}
print(math.difference(english))
print(english.difference(math))
运行结果:
{'xg', 'xx'}
{'dm', 'john'}
Process finished with exit code 0
集合的其他方法
1.交差补集
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
math = {'xm','xh','xg','xx'}
english ={'xm','xh','dm','john'}
print(math.symmetric_difference(english))
运行结果:
{'dm', 'john', 'xx', 'xg'}
Process finished with exit code 0
2.如果交集李没有重复的返回True
math = {'xm','xh','xg','xx'}
english ={'xd','xb','dm','john'}
print(math.isdisjoint(english))
运行结果:
True
Process finished with exit code 0
3.math 是 English的子集
math = {'xm','xh','xg','xx'}
english ={'xd','xb','dm','john'}
print(math.issubset(english))
运行结果:
False (因为不是,所以返回false)
Process finished with exit code 0
4.更新(可以更新多个值)
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
math = {'xm','xh','xg','xx'}
english ={'xd','xb','dm','john'}
math.update(english)
print(math)
运算结果:
{'xm', 'xh', 'john', 'xb', 'xd', 'dm', 'xx', 'xg'}
Process finished with exit code 0
ps:不可变集合
s = frozenset('hello')
print(s)
运行结果:
frozenset({'e', 'l', 'h', 'o'})
Process finished with exit code 0