Python基础–10
什么是集合
集合的创建
集合中元素不允许重复;集合中元素无序
s={23,25,43,32,23,123,43,34,23}
print(s)
print(type(s))
# {32, 34, 23, 123, 25, 43}
# <class 'set'>
s=set(range(6))
print(s,type(s))
# {0, 1, 2, 3, 4, 5} <class 'set'>
print(set([3,4,5,6,5]))
# {3, 4, 5, 6}列表转集合
print(set((3,4,5,3,2,34,3,32,2)))
# {32, 34, 2, 3, 4, 5}元组转集合,集合中元素无序
print(set('PYTHON'))
# {'Y', 'H', 'P', 'O', 'N', 'T'} 字符串序列转集合
print(set({1,2,3,4,2,3,4,5,124}))
{1, 2, 3, 4, 5, 124}
#不能用花括号定义空集合
print(type({}),{})
print(type(set()),set())
# <class 'dict'> {}
# <class 'set'> set()
集合的相关操作
s={10,20,30,40,50}
print(10 in s)
print(100 in s)
s.add(100)
print(s)
s.update({200,400,300})
print(s)
s.update([500,600])
print(s)
s.update((700,800))
print(s)
# {50, 20, 100, 40, 10, 30}
# {100, 40, 200, 10, 300, 400, 50, 20, 30}
# {100, 40, 200, 10, 300, 400, 50, 20, 500, 600, 30}
# {800, 100, 40, 200, 10, 300, 400, 50, 20, 500, 600, 700, 30}
s.remove(100)
print(s)
# s.remove(900) KeyError: 900
s.discard(900)
print(s)
s.pop()
print(s)
# s.pop(400) TypeError: set.pop() takes no arguments (1 given) 函数pop()
# {800, 40, 200, 10, 300, 400, 50, 20, 500, 600, 700, 30}
# {800, 40, 200, 10, 300, 400, 50, 20, 500, 600, 700, 30}
# {40, 200, 10, 300, 400, 50, 20, 500, 600, 700, 30}
s.clear()
print(s)
# set()
集合间的关系
s={10,20,30,40}
s1={20,10,40,30}
print(s1==s)
#True
s2={10,30}
s3={30,50}
print(s2.issubset(s))
print(s3.issubset(s))
# True
# False
print(s.issuperset(s2))
print(s.issuperset(s3))
# True
# False
s4={60,70,80}
print(s.isdisjoint(s1))
print(s.isdisjoint(s2))
print(s.isdisjoint(s4))
# False
# False
# True
集合的数据操作
#交集:intersection() 或 &
s1={10,20,30}
s2={23,30,20}
print(s1.intersection(s2))
print(s1 & s2)
# {20, 30}
# {20, 30}
#并集:union() 或 |
print(s1.union(s2))
print(s1 | s2)
# {20, 23, 10, 30}
# {20, 23, 10, 30}
#差集:difference() 或 -
s1={10,20,30,40}
s2={20,30,50}
print(s1.difference(s2))
print(s1-s2)
# {40, 10}
# {40, 10}
#对称差集:symmetric_difference() 或 ^
s1={10,20,30,40}
s2={20,30,50}
print(s1.symmetric_difference(s2))
print(s1 ^ s2)
# {40, 10, 50}
# {40, 10, 50}
集合生成式
#列表生成式
lst=[i*i for i in range(6)]
print(lst,type(lst))
#集合生成式
s={i for i in range(6)}
print(s,type(s))
# [0, 1, 4, 9, 16, 25] <class 'list'>
# {0, 1, 2, 3, 4, 5} <class 'set'>