自学Python2.5-基本数据类型-set集合

Python set集合

一、 set集合概述

①set集合,是一个无序且不重复的元素集合。
②集合对象是一组无序排列的可哈希的值,集合成员可以做字典中的键。
③集合支持用in和not in操作符检查成员,由len()内建函数得到集合的基数(大小), 用 for 循环迭代集合的成员。但是因为集合本身是无序的,不可以为集合创建索引或执行切片(slice)操作,也没有键(keys)可用来获取集合中元素的值。
④集合set是Python中一种基本数据类型,它分为可变集合(set)和不可变集合(frozenset)两种。

二、set的操作

1. set的创建

集合中set括号中需要的参数的数据类型有:序列(包括字符串、列表、元组),字典或者是另一个集合,但是不能是数值类型,如int类型。

s1=()  #创建空集合set()
print(s1)
s2=set(['carlos','alex','eric','tony']) #列表做参数
print(s2)
s3=set('carlos')#字符串做参数
print(s3)
s4=set((1,2,3))#元组做参数
print(s4)
s5=set({'name':'carlos','age':'26'})#元组做参数 , 只取值字典中的key
print(s5)

输出

()
{'tony', 'carlos', 'alex', 'eric'}
{'l', 'o', 'a', 's', 'r', 'c'}
{1, 2, 3}
{'age', 'name'}

s=set(['carlos','alex','eric','tony','carlos']) #set中的元素是无序不重复 的,可以利用这个特点去除列表中的重复元素
print(s)

输出
{'alex', 'carlos', 'tony', 'eric'}

2. set集合的添加

2.1 add(self, *args, **kwargs)把要传入的元素作为一个整体添加到集合中

s=set(['carlos','alex','eric','tony'])
print(s)
s.add('gary')
print(s)

输出

{'tony', 'carlos', 'alex', 'eric'}
{'tony', 'alex', 'gary', 'eric', 'carlos'}

2.2 update(self, *args, **kwargs) 要传入的元素拆分成单个字符,存于集合中,并去掉重复的字符

s=set(['carlos','alex','eric','tony'])
print(s)
s.update('amy')
print(s)

输出

{'tony', 'carlos', 'alex', 'eric'}
{'a', 'm', 'eric', 'tony', 'y', 'carlos', 'alex', 'gary'}

3.集合的删除 
   集合的删除操作使用的方法跟列表是一样的,使用的也是remove方法,若不存在,报错

s=set(['carlos','alex','eric','tony'])
print(s)
s.remove('alex')
print(s)

输出

{'tony', 'eric', 'alex', 'carlos'}
{'tony', 'eric', 'carlos'}

4. 集合的遍历

s=set(['carlos','alex','eric','tony'])
for i in s:
  print(i)

输出

tony
eric
alex
carlos

s=set(['carlos','alex','eric','tony'])
for idx, i in enumerate(s) :
  print(idx,i)

输出

0 tony
1 alex
2 eric
3 carlos

三、集合的一些操作符  

1.交集 python中求集合的交集使用的符号是“&”,返回连个集合的共同元素的集合,即集合的交集。 

s1=set('carlos')
print(s1)
s2=set('alex')
print(s2)
s=s1&s2
print(s)

输出

{'o', 's', 'r', 'c', 'l', 'a'}
{'x', 'l', 'a', 'e'}
{'l', 'a'}

2.并集(合集) Python中求集合的并集用的是符号“|”,返回的是两个集合所有的并去掉重复的元素的集合。

s1=set('carlos')
print(s1)
s2=set('alex')
print(s2)
s=s1|s2
print(s)

输出

{'s', 'r', 'c', 'o', 'l', 'a'}
{'e', 'l', 'a', 'x'}
{'s', 'x', 'r', 'c', 'o', 'e', 'l', 'a'}

3.差集  Python中差集使用的符号是减号“-”  ,返回的结果是在集合st1中但不在集合s2中的元素的集合

s1=set('carlos')
print(s1)
s2=set('alex')
print(s2)
s=s1-s2
print(s)

输出

{'l', 's', 'r', 'a', 'c', 'o'}
{'a', 'l', 'x', 'e'}
{'r', 'c', 's', 'o'}

4.查看两个集合的不同之处,使用的difference函数,等价于差集

   不同指的是集合s3相对于集合s1,不同的地方,也就是所有在集合s1中,而不再集合s2中的的元素组成的新集合。

s1=set('carlos')
s2=set('alex')
s=s1-s2
s3=s1.difference(s2)
print(s)
print(s3)

输出

{'r', 'o', 'c', 's'}
{'r', 'o', 'c', 's'}

5. 集合的范围判断

  集合可以使用大于(>)、小于(<)、大于等于(>=)、小于等于(<=)、等于(==)、不等于(!=)来判断某个集     合是否完全包含于另一个集合,也可以使用子父集判断函数。 返回值为True 或者False。

6. 集合的成员运算符  使用成员运算符,in和not in,判断某个对象是否是集合中的成员

s1=([1,2,3,4,5,])
result=1 in s1
print(result)
result=4 not in s1
print(result)

输出

True
False

7. 求集合的长度  使用len()函数

s1=([1,2,3,4,5,])
result=len(s1)
print(result)

输出 5

四、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(self, *args, **kwargs)    将元素 添加到集合s中,若重复则不进行任何操作

     update(self, *args, **kwargs) 将集合 x 并入原集合s中,x 还可以是列表,元组,字典等,x 可以有多个,用逗号分开

2、clear(self, *args, **kwargs)  删除 set 中的所有元素

3、copy(self, *args, **kwargs)  复制集合

4、difference(self, *args, **kwargs)  返回一个新的 set 包含 s1中有但是s2中没有的元素(生成新集合,不改变原集合)

     difference_update(self, *args, **kwargs) 返回一个新的 set 包含 s1和 s2中不重复的元素(改变原集合)

s1=set('carlosalexamy')
s2=set('alextong')
s3=s1.difference(s2)
s4=s1.difference_update(s3)
print(s3)
print(s4)

输出

{'s', 'c', 'm', 'r', 'y'}
None

5、discard(self, *args, **kwargs)    如果在 set “s”中存在元素 x, 则删除。若不存在,不会引发错误

s1=set(['carlos','alex','eric','tony'])
s1.discard('tony')
print(s1)

输出{'carlos', 'alex', 'eric'}

6、intersection(self, *args, **kwargs)  取交集,新建一个set

   intersection_update(self, *args, **kwargs) 取交集,修改原来set

7. isdisjoint(self, *args, **kwargs) 如果没有交集,返回Ture

8. issubset(self, *args, **kwargs)  是否是子集

9. issuperset(self, *args, **kwargs) 是否是父集

10. pop(self, *args, **kwargs)  删除并且返回 set “s”中的一个不确定的元素, 如果为空则引发 KeyError (在原集合拿走一个随机元素,并得到这个元素, 这个是两个动作)

s1=set(['carlos','alex','eric','tony'])
result=s1.pop()
print(s1)
print(result)

输出

{'carlos', 'tony', 'alex'}
eric

11. remove(self, *args, **kwargs)   从 set “s”中删除元素 x, 如果不存在则引发 KeyError(在原集合拿走一个指定元素,无返回值)

s1=set(['carlos','alex','eric','tony'])
result=s1.remove('alex')
print(s1)
print(result)

输出

{'carlos', 'tony', 'eric'}
None 

12.  symmetric_difference(self, *args, **kwargs) 取差集,新建一个set

       symmetric_difference_update(self, *args, **kwargs) 取差集,改变原来set

13.  union(self, *args, **kwargs)   取并集

 五、 举例子

 

posted on 2017-08-22 12:57  CARLOS_KONG  阅读(469)  评论(0编辑  收藏  举报

导航