set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
基 本 功 能 包 括 关 系 测 试 和 消 除 重 复 元 素 。
大括号 { } 或 set() 函数可以用来创建集合。
注意:想要创建空集合,你必须使用set() 而不是 {} 。{}用于创建空字典;
a = set('abracadabra')
a
{'a', 'b', 'c', 'd', 'r'}
b = set('alacazam')
b
{'a', 'c', 'l', 'm', 'z'}
#集合a中包含的元素,而集合b中不包含
a-b
{'b', 'd', 'r'}
#并集
a|b
{'a', 'b', 'c', 'd', 'l', 'm', 'r', 'z'}
#交集
a&b
{'a', 'c'}
#不同时包含于集合a和集合b的元素
a^b
{'b', 'd', 'l', 'm', 'r', 'z'}
s = {1}
type(s)
<class 'set'>
#从列表到集合
L1 = [1,1,2,4,3]
s = set(L1)
s
{1, 2, 3, 4}
#从tuple到set
T1 = (2,4,6,6,6,7)
s = set(T1)
s
{2, 4, 6, 7}
集合的基本操作:
(1)添加元素:s.add( x ) 将元素 x 添加到集合s中,若重复则不进行任何操作。
thisset = set(("Google", "Runoob", "Taobao"))
thisset.add("Facebook")
print(thisset)
{'Taobao', 'Facebook', 'Google', 'Runoob'}
还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等,语法格式如下:s.update(x)
thisset = set(("Google", "Runoob", "Taobao"))
thisset.update({1,3})
print(thisset)
{'Taobao', 1, 3, 'Google', 'Runoob'}
#x可以是多个,用逗号隔开
thisset.update([1,4],[5,6])
print(thisset)
{'Taobao', 1, 3, 'Google', 4, 5, 6, 'Runoob'}