8-集合

创建set

集合(set)是一个无序不重复元素的序列。

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

==用set()创建时,是2个括号==

1
thisset = set(("Google", "Runoob", "Taobao"))

添加元素

1
2
3
4
5
6
s.add( x )

>>>thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{'Taobao', 'Facebook', 'Google', 'Runoob'}
1
2
3
4
5
6
7
8
9
s.update( x )  //添加元素,且参数可以是列表,元组,字典等

>>>thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.update({1,3})
>>> print(thisset)
{1, 3, 'Google', 'Taobao', 'Runoob'}
>>> thisset.update([1,4],[5,6])
>>> print(thisset)
{1, 3, 4, 5, 6, 'Google', 'Taobao', 'Runoob'}

删除元素

1
s.remove( x )

随机删除集合中的一个元素:

1
s.pop()

判断元素是否在集合中存在

1
x in s

内置函数

1
len(s)  //计算集合 s 元素个数