>>> a={3,5}
>>> a
{3, 5}
>>> a=set(range(8,14))
>>> a
{8, 9, 10, 11, 12, 13}
>>> b=set([0,1,2,3,0,1,2,3,7,8])
>>> b
{0, 1, 2, 3, 7, 8}
>>> x=set() #空集合
>>> a
{8, 9, 10, 11, 12, 13}
>>> 11 in a
True
>>> 0 in a
False
>>> 13 not in a
False
>>> 17 not in a
True
>>> a
{8, 9, 10, 11, 12, 13}
>>> for data in a:
print(data)
8
9
10
11
12
13
>>> a
{8, 9, 10, 11, 12, 13}
>>> a.add(2)
>>> a
{2, 8, 9, 10, 11, 12, 13}
(2)集合对象的update()方法:添加多个元素
>>> a
{2, 8, 9, 10, 11, 12, 13}
>>> b={0,1,3,4,2}
>>> b
{0, 1, 2, 3, 4}
>>> a.update(b)
>>> a
{0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
>>> b.update(a)
>>> b
{0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
该方法不同于 remove() 方法,因为 remove() 方法在移除一个不存在的元素时会发生错误,而 discard() 方法不会。
>>> a
{1, 2, 4, 8, 9, 10, 11, 12, 13}
>>> a.discard(4)
>>> a
{1, 2, 8, 9, 10, 11, 12, 13}
>>> a.discard(0)
>>> a
{1, 2, 8, 9, 10, 11, 12, 13}
>>> a
{1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
>>> a.remove(3)
>>> a
{1, 2, 4, 8, 9, 10, 11, 12, 13}
>>> a.remove(0) #删除不存在的元素就会抛出异常
Traceback (most recent call last):
File "", line 1, in
a.remove(0) #删除不存在的元素就会抛出异常
KeyError: 0
>>> a
{0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
>>> a.pop() #删除并返回一个元素
0
>>> a
{1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
>>> a.pop(2) #pop方法不接收参数
Traceback (most recent call last):
File "", line 1, in
a.pop(2) #pop方法不接收参数
TypeError: set.pop() takes no arguments (1 given)
>>> a
{1, 2, 8, 9, 10, 11, 12, 13}
>>> a.clear()
>>> a
set()
>>> a
{1, 2, 8, 9, 10, 11, 12, 13}
>>> b
{0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
>>> a|b #并集
{0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
>>> a
{1, 2, 8, 9, 10, 11, 12, 13}
>>> b
{0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
>>> a&b #交集
{1, 2, 8, 9, 10, 11, 12, 13}
>>> a
{1, 2, 8, 9, 10, 11, 12, 13}
>>> b
{0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
>>> a-b
set()
>>> b-a
{0, 3, 4}
>>> a
{1, 2, 8, 9, 10, 11, 12, 13}
>>> b
{0, 1, 2, 3, 4, 8, 9, 10, 11, 12, 13}
>>> a^b
{0, 3, 4}