python集合有哪些方法

576次阅读
没有评论

python集合有哪些方法

python中的集合是一种常见的数据类型,下面是它的一些用法

一、集合的定义

s = set()  #定义空集合
s = {'a','b','c','d'}   #集合不是key-value  形的,无冒号

集合是无序的,没办法通过下标取值

二、集合赋值

s.add()
s = {'a','b','c','d'}s.add('ijk')  #注意add 与 update的区别# s.update('fgh')print(s)

输出结果:

{'d', 'ijk', 'c', 'b', 'a'}

s.update()

输出结果:

{'f', 'b', 'g', 'd', 'a', 'c', 'h'}

s = set()

s = set(‘cheeseshop’) print(s)

输出结果:

{'s', 'e', 'p', 'h', 'o', 'c'}

三、删除集合元素

s.remove()s = set('cheeseshop')s.remove('er')  # 删除不存在的会报错s.remove('e')print(s)
s.pop()  #随机删除一个
s.discard('er')  #如果删除的元素存在,删除,不存在不做处理

del s  # 删除集合

四、集合常用操作

s -= set('copy')   等价于  s = s - set('copy')

取交集

s.intersection(s1)   等价于  s & s1

取并集

s.union(s1)   等价于  s | s1

取差集

s.difference(s1)   等价于  s - s1

取对称差集

s.symmetric_difference(s1)   等价于 s^s1   取既不存在于s ,也不存在于s1中的元素

示例如下:

s = set('hi')
t = set('hello')
print(s.symmetric_difference(t))

输出结果:

{'e', 'i', 'l', 'o'}
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-12-10发表,共计812字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)