集合是无序的、不重复的数据集合,它本身是可变的,但里面的元素是不可变类型(这里要注意,即使是含有列表的元组也不可以,必须是完全不可变类型)
s1 = set({2,5,'hello',(2,5,'world')})
print(s1)
{(2, 5, 'world'), 2, 5, 'hello'}
s1 = set({2,5,'hello',(2,5,'world')})
s1.add('随机')
print('输出结果是:')
print(s1)
s1.update('分解元素')
print(s1)
输出结果是:
{2, 5, 'hello', '随机', (2, 5, 'world')}
{2, 5, 'hello', '随机', '素', '分', (2, 5, 'world'), '解', '元'}
s1 = set({2,5,'hello',(2,5,'world')})
res = s1.pop()
print('输出结果是:')
print(s1,res)
s1.remove(5)
print(s1)
s1.clear()
print(s1)
del s1
输出结果是:
{2, 5, 'hello'} (2, 5, 'world')
{2, 'hello'}
set()
对于集合来讲有几种运算方法:交集、并集、差集、反交集、子集、超集
s1 = {1,2,3,4,5}
s2 = {3,4,5,6,7}
print('交集:',s1 & s2)
print('交集:',s1.intersection(s2))
print('并集:',s1 | s2)
print('并集:',s1.union(s2))
print('差集:',s1 - s2)
print('差集:',s1.difference(s2))
print('反交集:',s1 ^ s2)
print('反交集:',s1.symmetric_difference(s2))
交集: {3, 4, 5}
交集: {3, 4, 5}
并集: {1, 2, 3, 4, 5, 6, 7}
并集: {1, 2, 3, 4, 5, 6, 7}
差集: {1, 2}
差集: {1, 2}
反交集: {1, 2, 6, 7}
反交集: {1, 2, 6, 7}
s1 = {1,2,3}
s2 = {1,2,3,4,5}
print(s1.issubset(s2))
print(s2.issuperset(s1))
True
True
使用frozenset(‘集合名’),可以把集合变成不可变集合