set

set 和 dict 类似,也是一组 key 的集合,但是 set 不保存 key 的值

要创建一个set,需要提供一个list作为输入集合:

>>> s = set([1,2,3])
>>> s
{1, 2, 3}

注意,传入的参数[1, 2, 3]是一个list,而显示的{1, 2, 3}只是告诉你这个set内部有1,2,3这3个元素,显示的顺序也不表示set是有序的。

使用其他的序列也可以创建set

>>> s = set((1,))
>>> s
{1}

>>> s = set({'name':'ginson','age':17,'height':173})
>>> s
{'name', 'age', 'height'}
#此处我以一个dict创建set,根据set的属性,只保留了key,没有value#

重复元素在set中自动被过滤:

>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}

这个特性似乎可以用来做点什么,比如去重 23333…

通过add(key)方法可以添加元素到set中,可以重复添加,但不会有效果:

>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4}

通过remove(key)方法可以删除元素:

>>> s.remove(4)
>>> s
{1, 2, 3}

set可以看成数学意义上的无序和无重复元素的集合,因此,两个set可以做数学意义上的交集、并集等操作:

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

####

咦咦咦咦,并集交集这个,在学list和tuple等序列的时候似乎没提到?应该也适用吧。

>>> L=[1,2,3]
>>> L2=[2,3,4]
>>> L & L2
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    L & L2
TypeError: unsupported operand type(s) for &: 'list' and 'list'
>>> L
[1, 2, 3]
>>> L | L2
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    L | L2
TypeError: unsupported operand type(s) for |: 'list' and 'list'

哦,并不适用

####

set和dict的唯一区别仅在于没有存储对应的value,但是,set的原理和dict一样,所以,同样不可以放入可变对象,因为无法判断两个可变对象是否相等,也就无法保证set内部“不会有重复元素”。

>>> s
{'name', 'age', 'height'}
>>> s.add(list(range(3)))
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    s.add(list(range(3)))
TypeError: unhashable type: 'list'
原文地址:https://www.cnblogs.com/ginsonwang/p/5727547.html