1. 程式人生 > >Python set

Python set

() 數據庫 true union repr 刪除 差集 交集 memory

1、創建一個set

# set和dict類似,也是一組key的集合,但不存儲value。由於key不能重復,所以,在set中,沒有重復的key。
>>> s1 = set([root, gm, evescn, gm])

2、查看set

>>> s1
{gm, evescn, root}

3、查看set可進行的操作

>>> dir(s1)
[__and__, __class__, __contains__, __delattr__, __dir__, __doc__, __eq__
, __format__, __ge__, __getattribute__, __gt__, __hash__, __iand__, __init__, __ior__, __isub__, __iter__, __ixor__, __le__, __len__, __lt__, __ne__, __new__, __or__, __rand__, __reduce__, __reduce_ex__, __repr__, __ror__, __rsub__, __rxor__, __setattr__
, __sizeof__, __str__, __sub__, __subclasshook__, __xor__, add, clear, copy, difference, difference_update, discard, intersection, intersection_update, isdisjoint, issubset, issuperset, pop, remove, symmetric_difference, symmetric_difference_update, union,
update]

技術分享
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
        """ 刪除當前set中的所有包含在 new set 裏的元素 """
        """ 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
        """ 取交集,新創建一個set """
        """
        Return the intersection of two or more sets as a new set.
        
        (i.e. elements that are common to all of the sets.)
        """
        pass

    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ 取交集,修改原來set """
        """ Update a set with the intersection of itself and another. """
        pass

    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ 如果沒有交集,返回true  """
        """ 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, y): # real signature unknown; restored from __doc__
        """ x.__and__(y) <==> x&y """
        pass

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

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

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

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__(‘name‘) <==> x.name """
        pass

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

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

    def __iand__(self, y): # real signature unknown; restored from __doc__
        """ x.__iand__(y) <==> x&=y """
        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, y): # real signature unknown; restored from __doc__
        """ x.__ior__(y) <==> x|=y """
        pass

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

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

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

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

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

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

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

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

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

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

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

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

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

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

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

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

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

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

    __hash__ = None
set

4、常用的set操作

# 添加一個新的key

>>> s1
{gm, evescn, root}
>>> s1.add(gm) >>> s1 {gm, evescn, root}

# s1和s2對比

>>> s1
{gm, evescn, root}
>>> s2
{gm, root, hlr}

>>> s1.difference(s2)     # s1差s2
{evescn}
>>> s2.difference(s1)     # s2差s1
{hlr}
>>> s1.intersection(s2)   # s1交s2
{gm, root}
>>> s1.union(s2)          # s1並s2    
{gm, root, hlr, evescn}    

# difference和difference_update的區別
# difference把差異結果返回,但不修改原集合
# difference_update修改原集合
# 其他操作,例如:intersection和intersection_update也是類似的

>>> s1
{gm, evescn, root}
>>> s2
{gm, root, hlr}

>>> s2.difference(s1)
{hlr}
>>> s3 = s2.difference(s1)
>>> s3        # s3獲取到了difference返回的結果
{hlr}
>>> s2        # s2未被修改
{gm, root, hlr}

>>> s4 = s2.difference_update(s1)
>>> s4        # difference_updat沒有返回結果
>>> s2        # s2已經被修改
{hlr}                                                        

# pop和remove的區別
# pop:刪除一個key值,並且刪除的key可以使用變量來獲取,不支持刪除指定的key值
# remove:刪除指定的key值,不能獲取到刪除的key值,不指定key值會報錯

>>> s1
{gm, evescn, root, abc}

>>> set1 = s1.pop(gm)        # 指定key值報錯
Traceback (most recent call last):
  File "<pyshell#158>", line 1, in <module>
    set1 = s1.pop(gm)
TypeError: pop() takes no arguments (1 given)

>>> set1 = s1.pop()
>>> set1        # 獲取到刪除的key
gm

>>> s1
{evescn, root, abc}
>>> set2 = s1.pop()
>>> set2
evescn

>>> s1
{root, abc}
>>> set3 = s1.remove()        # 刪除時,不指定key值報錯
Traceback (most recent call last):
  File "<pyshell#152>", line 1, in <module>
    set3 = s1.remove()
TypeError: remove() takes exactly one argument (0 given)

>>> set3 = s1.remove(abc)
>>> set3        # 不能獲取到刪除的key
>>> s1
{root}

# 差集和對稱差的區別

>>> s1
{gm, evescn, root}
>>> s2
{gm, hlr, root}

# 差集

>>> ret1 = s1.difference(s2)    
>>> ret2 = s2.difference(s1) 

>>> print(ret1)
{evescn}
>>> print(ret2)
{hlr}
# 簡單的理解如何計算出差集的

for item in s1:
    if item in s2:
        del "s1.item"

#
對稱差 ret1 = s1.symmetric_difference(s2) ret2 = s2.symmetric_difference(s1) >>> print(ret1) {evescn, hlr} >>> print(ret2) {evescn, hlr}
# 如何計算出對稱差的

for item in s1:
    if item not in s2:
        add "ret1.item"

for item in s2:
    if item not in s1:
        add "ret1.item"

5、練習:尋找差異

 1 # 數據庫中原有
 2 old_dict = {
 3     "#1":{ hostname:c1, cpu_count: 2, mem_capicity: 80 },
 4     "#2":{ hostname:c1, cpu_count: 2, mem_capicity: 80 }
 5     "#3":{ hostname:c1, cpu_count: 2, mem_capicity: 80 }
 6 }
 7  
 8 # cmdb 新匯報的數據
 9 new_dict = {
10     "#1":{ hostname:c1, cpu_count: 2, mem_capicity: 800 },
11     "#3":{ hostname:c1, cpu_count: 2, mem_capicity: 80 }
12     "#4":{ hostname:c2, cpu_count: 2, mem_capicity: 80 }
13 }
14  
15 需要刪除:?
16 需要新建:?
17 需要更新:? 註意:無需考慮內部元素是否改變,只要原來存在,新匯報也存在,就是需要更新

結果:

 1 交集、差集即為需要的結果
 2 
 3 交集:
 4     需要更新或不變的數據
 5 
 6 差集:
 7     old差new  -->  刪除的數據
 8     new差old  -->  新增的數據
 9 
10 # 獲取字典的key值
11 old = set(old_dict.keys())
12 new = set(new_dict.keys())
13 
14 update_set = old.intersection(new)           #要更新的集合
15 delete_set = old.difference(update_set) )    #要刪除的集合
16 add_set = new.difference(update_set)         #要添加的集合

Python set