您的位置:首页 > 理论基础 > 数据结构算法

python的第四数据结构-set

2019-03-21 21:39 78 查看

什么是集合呢?

说到集合,我首先想到了高中的数学。高中,人生学习中最繁忙的一段时光。直到现在,我能回忆起最多的就是学习、学习、还是读书……言归正传,高一时的数学,我们就接触到了集合。书中应该是这样定义的:

集合:由一个或多个确定的元素所构成的整体。若x是集合A的元素,则记作x∈A。

集合中的元素有三个特征:

1. 确定性:集合中的元素必须是确定的;

2. 互异性:集合中的元素互不相同,例如:集合A={1,a},则a不能等于1);

3. 无序性:集合中的元素没有先后之分,例如:集合{3,4,5}和{3,5,4}算作同一个集合。

Python 3.x中的set特征与数学中类似。我们之前学过list、tuple以及dict。其实,set与dict大致相同,但set没有Value,只有key。因此,set只是一组key的集合。由于key不能重复,所以,在set中,没有重复的key。

创建集合

1.1 创建空集合

在集合中,创建空集合(set)必须使用函数set()。

>>>a = set()
>>>a
set()
>>>type(a)
<class 'set'>

注:不能使用{},{}用于创建空字典。
 
 1.2 创建非空集合
 
  非空集合可以用大括号{}或 set() 函数来创建。
  #创建集合

>>>a={'a','b','c','d'}
>>>b=set('abcdefabcd')
>>>c=set({'a':1,'b':2,'c':3})
>>>d=set(['a','b','c','a'])
#运行结果
>>>print(a,type(a))
{'c', 'd', 'b', 'a'} <class 'set'>
>>>print(b,type(b))
{'f', 'e', 'b', 'c', 'd', 'a'} <class 'set'>
>>>print(c,type(c))
{'b', 'a','c'} <class 'set'>
>>>print(d,type(d))
{'c', 'b', 'a'} <class 'set'>

特别地,set中的元素是无序的,并且重复元素在set中自动被过滤

1 #set中重复元素被自动过滤
2 >>>s = {1,2,,1,2,4,4,3,3}
3 >>>s
4 {1,2,3,4}

功能属性
  set有很多很多的功能属性。你们不信?不信的话,继续往下看呗~~~

  set功能属性如下:
  class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object

Build an unordered collection of unique elements.
"""
def add(self, *args, **kwargs): # real signature unknown
"""
Add an element to a set.

This has no effect if the element is already present.
"""
pass

def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. """
pass

def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. """
pass

def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set.

(i.e. all elements that are in this set but not the others.)
"""
pass

def difference_update(self, *args, **kwargs): # real signature unknown
""" Remove all elements of another set from this set. """
pass

def discard(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set if it is a member.

If the element is not a member, do nothing.
"""
pass

def intersection(self, *args, **kwargs): # real signature unknown
"""
Return the intersection of two sets as a new set.

(i.e. all elements that are in both sets.)
"""
pass

def intersection_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the intersection of itself and another. """
pass

def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection. """
pass

def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set. """
pass

def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. """
pass

def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
"""
pass

def remove(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set; it must be a member.

If the element is not a member, raise a KeyError.
"""
pass

def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set.

(i.e. all elements that are in exactly one of the sets.)
"""
pass

def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the symmetric difference of itself and another. """
pass

def union(self, *args, **kwargs): # real signature unknown
"""
Return the union of sets as a new set.

(i.e. all elements that are in either set.)
"""
pass

def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others. """
pass

def __and__(self, *args, **kwargs): # real signature unknown
""" Return self&value. """
pass

def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x. """
pass

def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass

def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass

def __ge__(self, *args, **kwargs): # real signature unknown
""" Return self>=value. """
pass

def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass

def __iand__(self, *args, **kwargs): # real signature unknown
""" Return self&=value. """
pass

def __init__(self, seq=()): # known special case of set.__init__
"""
set() -> new empty set object
set(iterable) -> new set object

Build an unordered collection of unique elements.
# (copied from class doc)
"""
pass

def __ior__(self, *args, **kwargs): # real signature unknown
""" Return self|=value. """
pass

def __isub__(self, *args, **kwargs): # real signature unknown
""" Return self-=value. """
pass

def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass

def __ixor__(self, *args, **kwargs): # real signature unknown
""" Return self^=value. """
pass

def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass

def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass

def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass

@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object.  See help(type) for accurate signature. """
pass

def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass

def __or__(self, *args, **kwargs): # real signature unknown
""" Return self|value. """
pass

def __rand__(self, *args, **kwargs): # real signature unknown
""" Return value&self. """
pass

def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass

def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass

def __ror__(self, *args, **kwargs): # real signature unknown
""" Return value|self. """
pass

def __rsub__(self, *args, **kwargs): # real signature unknown
""" Return value-self. """
pass

def __rxor__(self, *args, **kwargs): # real signature unknown
""" Return value^self. """
pass

def __sizeof__(self): # real signature unknown; restored from __doc__
""" S.__sizeof__() -> size of S in memory, in bytes """
pass

def __sub__(self, *args, **kwargs): # real signature unknown
""" Return self-value. """
pass

def __xor__(self, *args, **kwargs): # real signature unknown
""" Return self^value. """
pass

__hash__ = None

set功能属性虽多,但平时常用的也就那么几个。

常用属性
  1. 添加元素

在集合中添加元素,可以使用add()方法,并且不生成一个新的集合。
  #添加元素:add()

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

add()方法可以向set中添加元素,可以重复添加,但不会有效果。

2. 删除元素

set中利用remove()方法可以删除集合中的元素。
  #删除元素

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

3. 清空元素

clear()方法可以清空set中的元素。
  #清空元素

>>>a = {1,2,3,4}
>>>b = a.clear()
>>>print(a,type(a))
set() <class 'set'>
>>>print(b,type(b))
None <class 'NoneType'>

4. 复制元素

copy()方法只能浅拷贝set中的元素,并生成一个新的集合。
  #浅拷贝:copy()

>>>a = {1,(9,2),3}
>>>b = a.copy()
>>>print(a,id(a))
{(9, 2), 1, 3} 2097937619880
>>>print(b,id(b))
{(9, 2), 1, 3} 2097937620776

#赋值
>>>s = {1,2,3,4}
>>>d = s
>>>print(s,id(s))
{1, 2, 3, 4} 2097937785128
>>>print(d,id(d))
{1, 2, 3, 4} 2097937785128

5. pop()

pop()方法用于从set中随机取一个元素。记住,是随机的~~~

#pop()方法
>>>s = {1,2,3,4,5,'g','s'}
>>>s.pop()
'g'
>>>s.pop()
3

6. set集合操作

set与数学中的集合类似,是无序的和无重复元素的集合。因此,在Python中,set可以进行交集、并集、补集等操作。
  
集合操作

#set集合操作
>>>s = {1,2,3,4}
>>>d = {2.3.5.6}
>>>s & d
{2.3}
>>>s | d
{1,2,3,4,5,6}
>>>s - d
{1,4}
>>>d - s
{5,6}

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

“思想者”

set中存储着key,集合中不能放入可变的对象。之前的文章也说过:tuple是不可变的,而list是可变的。因此,set中是可以存储tuple的。这是真的吗?

时间是检验真理的唯一标准。下面请看示例代码:

#tuple可以作为集合中的元素
>>>s = {(1,),(1,2,3),1,2,'g'}
>>>s
{(1,),(1,2,3),1,2,'g'}

#tuple也有失灵的时候
>>>t = (1,2,[1,2,3],4)
>>>type(t)
<class 'tuple'>
>>>d = {1,2,(1,2,[1,2,3],4)}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: