Python: set实例透析

时间:2022-06-01
本文章向大家介绍Python: set实例透析,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

开公众号啦,分享读书心得,欢迎一起交流成长。

Python里的 set数据类型

set是无序unique值的集合,常用来去重,检验membership等。set类似一个词典,但只有键key,没有值value,好多操作也类似,但不支持索引,切片等操作。

a = set([1,2,3,1])
b = set([2,3,4])
a
{1, 2, 3}
print b
set([2, 3, 4])

常见操作

a
{1, 2, 3}
len(a)
3
2 in a
True
遍历
# 像遍历字典一样
for i in a:
    print i,
1 2 3

增加

a.add(4)
a
{1, 2, 3, 4}

删除

# a.remove(el), if not found, raise error
a.remove(4)
a
{1, 2, 3}
# a.discard(el), if not found, do nothing
a.discard(4)

pop

a.pop()
1
a
{2, 3}

交集

a.intersection(b)
{2, 3}

差集

# a - b
a.difference(b)
set()
# b - a
b.difference(a)
{4}

集合关系

a.issubset(b)
True
b.issuperset(a)
True

清空

a.clear()
a
set()