Python的set和其他语言类似,是一个无序不重复元素集,基本功能包括关系测试和消除元素;
-
add:添加一个元素到集合;
a =set()
a.add('aa')
print(a)
{'aa'}
-
clear:清除集合里面所有的元素;
a =set(['aa','bb',12,'aa'])
print(a)
{'aa',12,'bb'}
a.clear()
print(a)
set()
-
copy:浅复制集合生成一个新的集合;
a =set(['aa','bb',12,'aa'])
b = a.copy()
print(b)
{'aa',12,'bb'}
-
difference:差集,返回由两个或多个集合中不同的元素组成一个新的集合;
a = set(['aa','bb',11])
b = set(['bb','cc',22])
ret1 = a.difference(b) #a和b对比,返回a存在b不存在的元素;
ret2 = b.difference(a) #b和a对比,返回b存在a不存在的元素;
print(ret1)
{11,'aa'}
print(ret2)
{22,'cc'}
-
difference_update:差集,从当前集合中移除其它集合中所拥有的元素;
a = set(['aa','bb',11])
b = set(['bb','cc',22])
ret1 = a.difference_update(b) #a和b对比,返回a中存在b不存在的元素,并更新自己的集合;
print(a)
{11,'aa'}
-
discard:删除指定的元素,如果不存在不报错;
a = set(['aa','bb',11])
b = a.discard('aa')
c = a.discard('dd')
d = a.discard('')
print(a)
{11,'bb'}
print(b)
None
print(c)
None
print(d)
None
-
intersection:交集,返回由两个或多个集合中相同的元素组成一个新的集合;
a = set(['aa','bb',11])
b = set(['bb','cc',22])
ret1 = a.intersection(b) #a和b相比,
返回a存在b也存在的元素;ret2 = b.intersection(a)
#b和a对比,返回b存在a也存在的元素;- print(a)
- {11, 'aa', 'bb'}
- print(b)
- {'cc', 22, 'bb'}
print(ret1)
{'bb'}
print(ret2)
{'bb'}
-
intersection_update:交集,从当前集合中移除其它集合中不拥有的元素;
a = set(['aa','bb',11])
b = set(['bb','cc',22])
ret1 = a.intersection_update(b)
print(a)
{'bb'}
print(ret1)
None
- isdisjoint:如果两个集合没有交集返回True;
a = set(['aa','bb',11])
b = set(['aa','cc',22])
x = set(['dd','cc',22])
a.isdisjoint(b) #a与b是否有交集,有返回False;
False
a.isdisjoint(x)
#a与x是否有交集,没有返回True;True
b.isdisjoint(a)
False
x.isdisjoint(a)
True
- issubset:判断a集合是否是b集合的子集;
a = set(['aa','bb',11])
b = set(['aa','bb',11,'dd'])
c = set(['bb',22])
a.issubset(b) #a是否是b的子集,是则返回True;
True
c.issubset(b) #c是否是b的子集,不是则返回False;
False
- issuperset:判断a集合是否是b集合的父集;
a = set(['aa','bb',11,'cc',22])
b =set(['aa',11])
c =set(['aa',11,'dd'])
a.issuperset(b) #a是否是b的父集,是则返回True;
True
a.issuperset(c)
#a是否是c的父集,不是则返回False;False
- pop:随机删除集合中的一个元素;
a = set(['aa','bb',11,'cc',22])
print(a)
{'cc',11,'aa',22,'bb'}
a.pop()
'cc'
print(a)
{11,'aa',22,'bb'}
- remove:删除集合中指定的一个元素,如果不存在不报错;;
a = set(['aa','bb',11,'cc',22])
a.remove('aa')
print(a)
{'cc',11,22,'bb'}
- symmetric_difference:对称差,返回两个集合的差集,生成新的集合;
a = set(['aa','bb',11])
b = set(['aa,','cc',22])
ret1 = a.symmetric_difference(b)
ret2 = b.symmetric_difference(a)
print(ret1)
{'bb',11,'aa','aa,',22,'cc'}
print(ret2)
{'bb',11,'aa','aa,',22,'cc'}
print(a)
{11,'aa','bb'}
print(b)
{'aa,',22,'cc'}
- symmetric_difference_update:对称差,返回两个几个的差集,不生成新的集合;
a = set(['aa','bb',11])
b = set(['aa,','cc',22])
ret1 = a.symmetric_difference_update(b)
print(ret1)
None
print(a)
{'bb',11,'aa','aa,',22,'cc'}
- union:返回a和b的并集;
a = set(['aa','bb',11])
b = set(['aa,','cc',22])
c = a.union(b)
print(c)
{'aa,',22,'bb',11,'aa','cc'}
- update:更新自身集合;
a = set(['aa','bb',11])
b = set(['aa,','cc',22])
b.update(a)
print(b)
{'aa,',22,'bb',11,'aa','cc'}