set() 函数创建一个无序不重复元素集。
s = set('klvchen')
print(s)
运行结果:
{'n', 'h', 'c', 'e', 'l', 'k', 'v'}
s1 = ['klvchen', 'aa', 'klvchen']
print(set(s1))
运行结果:
{'klvchen', 'aa'}
列表 通过 集合 进行去重操作
s1 = ['klvchen', 'aa', 'klvchen']
s2 = set(s1)
print(s2, type(s2))
s = list(s2)
print(s, type(s))
运行结果:
{'aa', 'klvchen'} <class 'set'>
['aa', 'klvchen'] <class 'list'>
判断元素是否在集合内
s = { 2, 3, 'klvchen'}
print(2 in s)
print('klvchen' in s)
print('klv' in s)
运行结果:
True
True
False
集合添加新元素
add()方法
s = { 2, 3, 'klvchen'}
s.add(1)
print(s)
运行结果:
{1, 2, 3, 'klvchen'}
update()方法
s = { 2, 3, 'klvchen'}
s.update('hello') #字符串会被拆分
print(s)
运行结果:
{2, 3, 'e', 'h', 'o', 'klvchen', 'l'}
s = { 2, 3, 'klvchen'}
s.update(['hello']) #在数组内的字符串被认为是一个整体
print(s)
运行结果:
{'klvchen', 2, 3, 'hello'}
集合删除
pop()随机弹出一个元素
s = { 2, 3, 'klvchen'}
s.pop()
print(s)
运行结果:
{2, 3}
clear()清空集合元素
s = { 2, 3, 'klvchen'}
s.clear()
print(s)
运行结果:
set()
del() 删除集合
s = { 2, 3, 'klvchen'}
del(s)
print(s)
运行结果:
NameError: name 's' is not defined
集合求交集
a = set([1, 2, 3, 4, 5])
b = set([4, 5, 6, 7, 8])
print(a.intersection(b))
print(a & b)
运行结果:
{4, 5}
{4, 5}
集合求并集
a = set([1, 2, 3, 4, 5])
b = set([4, 5, 6, 7, 8])
print(a.union(b))
print(a | b)
运行结果:
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}
集合求差集
a = set([1, 2, 3, 4, 5])
b = set([4, 5, 6, 7, 8])
print(a.difference(b))
print(a - b)
print(b.difference(a))
print(b - a)
运行结果:
{1, 2, 3}
{1, 2, 3}
{8, 6, 7}
{8, 6, 7}
a = set([1, 2, 3, 4, 5])
b = set([4, 5, 6, 7, 8])
print(a.symmetric_difference(b)) #对称差集
print( a ^ b)
运行结果:
{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}
集合超集和子集
a = set([4, 5, 6, 7, 8])
b = set([4, 5])
print(a.issuperset(b)) # 判断 a 是否是 b 的超集
print(b.issubset(a)) # 判断 b 是否是 a 的子集
运行结果:
True
True