python之路-基礎篇-day3

来源:http://www.cnblogs.com/CongZhang/archive/2016/01/18/5137919.html
-Advertisement-
Play Games

今日所講知識點總結:1、set集合2、collectionsPython擁有一些內置的數據類型,比如str, int, list, tuple, dict等, collections模塊在這些內置數據類型的基礎上,提供了幾個額外的數據類型:1)Counter:計數器2)OrderedDict:有序字...


今日所講知識點總結:

1、set集合

2、collections

Python擁有一些內置的數據類型,比如str, int, list, tuple, dict等, collections模塊在這些內置數據類型的基礎上,提供了幾個額外的數據類型:

1)Counter:計數器

2)OrderedDict:有序字典

3)defaultdict:預設字典

4)namedtuple:可命名元組

5)deque:雙向隊列

 

set集合

set集合是一個元素不重覆的無序集合。類似於字典的key組成的一個無序集合

set小案例:

下麵是兩組字典類型的數據,分別代表3台伺服器的硬體情況,old_dict代表之前記錄的數據,new_dict代表新記錄的數據,這裡要通過set列印出有哪些需要更新,刪除,最新添加的數據

old_dict = {
    "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
    "#2": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
    "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
}
new_dict = {
    "#1": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 800},
    "#3": {'hostname': 'c1', 'cpu_count': 2, 'mem_capicity': 80},
    "#4": {'hostname': 'c2', 'cpu_count': 2, 'mem_capicity': 80},
}


old_set = set(old_dict)
new_set = set(new_dict)

# 交集--兩個都包含的
# 更新
update_set = old_set.intersection(new_set)
print(update_set)

# 前面有,後面沒有的
# 刪除---源數據有,新數據沒有
old = old_set.difference(update_set)
print(old)

# 前面有,後面沒有的
# 新加---源數據沒有,新數據有
new = new_set.difference(update_set)
print(new)


# 非並集----兩個set集合都不存在的
print(old_set.symmetric_difference(new_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.
        """
        """
        像集合添加一個元素,只接受一個元素
        >>> a = set([1, 2, 3, 4, 5, 6])
        >>> a
        {1, 2, 3, 4, 5, 6}
        >>> a.add(1)
        >>> a           # 因為set集合會過濾掉重覆的,所以重覆的值只會出現一次
        {1, 2, 3, 4, 5, 6}
        >>> a.add(100)
        >>> a
        {1, 2, 3, 4, 5, 6, 100}

        # 添加多個值會出錯
        >>> a.add([55,66])
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: unhashable type: 'list'
        >>> a.add(55, 66)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: add() takes exactly one argument (2 given)
        """

        pass

    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. """
        """
        清空序列
        >>> a
        {1, 2, 3, 4, 5, 6, 100}
        >>> a.clear()
        >>> a
        set()
        """
        pass

    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. """
        """
        淺copy
        >>> a = set([1, 2, 3, 4, 5, 6])
        >>> a
        {1, 2, 3, 4, 5, 6}
        >>> b = a.copy()
        >>> b
        {1, 2, 3, 4, 5, 6}
        """
        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.)
        """
        """
        前者有,後者沒有的
        >>> a = set([1, 2, 3, 4, 5, 6])
        >>> b = set([3, 4, 5, 6, 7, 8])
        >>> a
        {1, 2, 3, 4, 5, 6}
        >>> a.difference(b)     # 返回a中有,b中沒有的
        {1, 2}
        >>> b.difference(a)     # 返回b中有,a中沒有的
        {8, 7}
        """
        pass

    def difference_update(self, *args, **kwargs): # real signature unknown
        """ Remove all elements of another set from this set. """
        """
        將前者有,後者沒有的重新賦值給前者
        >>> a = set([1, 2, 3, 4, 5, 6])
        >>> b = set([3, 4, 5, 6, 7, 8])
        >>> a.difference_update(b)
        >>> a
        {1, 2}

        """
        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.
        """
        """
        從集合中刪除一個元素,如果該元素不存在,則什麼都不做
        >>> a
        {1, 2, 3, 4, 5, 6}
        >>> a.discard(2)
        >>> a
        {1, 3, 4, 5, 6}
        >>> a.discard(10)
        >>> a
        {1, 3, 4, 5, 6}
        """
        pass

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

        (i.e. elements that are common to all of the sets.)
        """
        """
        交集,將兩個序列中都包含的元組組成一個新的set集合
        >>> a
        {1, 2, 3, 4, 5, 6}
        >>> b
        {3, 4, 5, 6, 7, 8, 9}
        >>> a.intersection(b)
        {3, 4, 5, 6}
        """
        pass

    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another. """
        """
        交集,將兩個序列中都包含的元組組成一個新的set集合,並且將這個新的集合重新賦值給前面的對象
        >>> a
        {1, 2, 3, 4, 5, 6}
        >>> b
        {3, 4, 5, 6, 7, 8, 9}
        >>> a.intersection_update(b)
        >>> a
        {3, 4, 5, 6}
        """
        pass

    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection. """
        """
        如果兩個集合沒有交集,則返回True,否則返回False
        >>> a
        {100}
        >>> b
        {3, 4, 5, 6, 7, 8, 9}
        >>> a.isdisjoint(b)
        True

        >>> a
        {3, 4, 5, 6}
        >>> b
        {3, 4, 5, 6, 7, 8, 9}
        >>> a.isdisjoint(b)
        False
        """
        pass

    def issubset(self, *args, **kwargs): # real signature unknown
        """ Report whether another set contains this set. """
        """
        如果前面是後面的子集,返回True,否則返回False
        >>> a
        {4, 5, 6}
        >>> b
        {3, 4, 5, 6, 7, 8, 9}
        >>> a.issubset(b)
        True


        >>> a
        {1, 2, 3, 4, 5, 6}
        >>> b
        {3, 4, 5, 6, 7, 8, 9}
        >>> a.issubset(b)
        False
        """
        pass

    def issuperset(self, *args, **kwargs): # real signature unknown
        """ Report whether this set contains another set. """
        """
        與issubset 相反,前面是後面的父集時,返回True,否則返回False
        >>> a
        {4, 5, 6}
        >>> b
        {3, 4, 5, 6, 7, 8, 9}
        >>> a.issuperset(b)
        False
        >>> b.issuperset(a)
        True
        """
        pass

    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty.
        """
        """
        隨機刪除一個元素,可以對a.pop()進行賦值,如果該集合為空,則返回KeyError
        >>> b
        {3, 4, 5, 6, 7, 8, 9}
        >>> c = b.pop()
        >>> c
        3
        """
        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.
        """
        """
        移除一個指定的元素,如果該元素不存在或者該序列為空則返回KeyError
        >>> b
        {4, 5, 6, 7, 8, 9}
        >>> b.remove(100)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        KeyError: 100
        >>> b.remove(4)
        >>> b
        {5, 6, 7, 8, 9}
        """
        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.)
        """
        """
        非交集,兩個序列的和減去交集的剩下的序列
        >>> a
        {1, 2, 3, 4, 5, 6, 7}
        >>> b
        {4, 5, 6, 7, 8, 9, 10}
        >>> a.symmetric_difference(b)
        {1, 2, 3, 8, 9, 10}
        """
        pass

    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. """
        """
        非交集,將兩個序列的和減去交集的剩下的序列賦值給前者
        >>> a
        {1, 2, 3, 4, 5, 6, 7}
        >>> b
        {4, 5, 6, 7, 8, 9, 10}
        >>> a.symmetric_difference_update(b)
        >>> a
        {1, 2, 3, 8, 9, 10}
        """
        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.)
        """
        """
        將序列複製一份出來
        >>> a.union()
        {1, 2, 3, 8, 9, 10}
        >>> b = a.union()
        >>> id(a)
        2443572810696
        >>> id(b)
        2443572812712
        """
        pass

    def update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. """
        """
        更新這個序列
        >>> a
        {1, 2, 3, 8, 9, 10}
        >>> a.update([1,2,3,4,5,6,7,8,9,10])
        >>> a
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        """
        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

 

collections系列

1、collections.Counter(dict)
Counter是對字典類型的補充,用於追蹤值的出現次數,稱之為計數器。
將傳入的數據變成一個序列,對序列中的每一個值進行處理,返回一個字典,字典包含每個元素在這個序列中出現的次數

使用Counter需要先導入collections

import collections
例如:
obj = collections.Counter('fdafdafdafdsafdahfdjahffdja')
print(obj)

返回結果:
Counter({'f': 8, 'a': 7, 'd': 7, 'j': 2, 'h': 2, 's': 1})

源碼:

class Counter(dict):
    '''Dict subclass for counting hashable items.  Sometimes called a bag
    or multiset.  Elements are stored as dictionary keys and their counts
    are stored as dictionary values.

    # 統計每一個元素出現的次數,字元串是一個字元串數組
    >>> c = Counter('abcdeabcdabcaba')  # count elements from a string
    >>> c
    Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

    # 返回序列中的前3組數據
    >>> c.most_common(3)                # three most common elements
    [('a', 5), ('b', 4), ('c', 3)]

    >>> sorted(c)                       # list all unique elements
    ['a', 'b', 'c', 'd', 'e']

    >>> ''.join(sorted(c.elements()))   # list elements with repetitions
    'aaaaabbbbcccdde'
    >>> sum(c.values())                 # total of all counts
    15

    >>> c['a']                          # count of letter 'a'
    5
    >>> for elem in 'shazam':           # update counts from an iterable
    ...     c[elem] += 1                # by adding 1 to each element's count
    >>> c['a']                          # now there are seven 'a'
    7
    >>> del c['b']                      # remove all 'b'
    >>> c['b']                          # now there are zero 'b'
    0

    >>> d = Counter('simsalabim')       # make another counter
    >>> c.update(d)                     # add in the second counter
    >>> c['a']                          # now there are nine 'a'
    9

    >>> c.clear()                       # empty the counter
    >>> c
    Counter()

    Note:  If a count is set to zero or reduced to zero, it will remain
    in the counter until the entry is deleted or the counter is cleared:

    >>> c = Counter('aaabbc')
    >>> c['b'] -= 2                     # reduce the count of 'b' by two
    >>> c.most_common()                 # 'b' is still in, but its count is zero
    [('a', 3), ('c', 1), ('b', 0)]

    '''
    # References:
    #   http://en.wikipedia.org/wiki/Multiset
    #   http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
    #   http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
    #   http://code.activestate.com/recipes/259174/
    #   Knuth, TAOCP Vol. II section 4.6.3

    def __init__(*args, **kwds):
        '''Create a new, empty Counter object.  And if given, count elements
        from an input iterable.  Or, initialize the count from another mapping
        of elements to their counts.

        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args

        '''
        if not args:
            raise TypeError("descriptor '__init__' of 'Counter' object "
                            "needs an argument")
        self = args[0]
        args = args[1:]
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        super(Counter, self).__init__()
        self.update(*args, **kwds)

    def __missing__(self, key):
        'The count of elements not in the Counter is zero.'
        # Needed so that self[missing_item] does not raise KeyError
        return 0

    def most_common(self, n=None):
        '''List the n most common elements and their counts from the most
        common to the least.  If n is None, then list all element counts.

        列出序列最靠前的n組數據,如果n為空,則輸出全部的序列
        >>> Counter('abcdeabcdabcaba').most_common(3)
        [('a', 5), ('b', 4), ('c', 3)]

        '''
        # Emulate Bag.sortedByCount from Smalltalk
        if n is None:
            return sorted(self.iteritems(), key=_itemgetter(1), reverse=True)
        return _heapq.nlargest(n, self.iteritems(), key=_itemgetter(1))

    def elements(self):
        '''Iterator over elements repeating each as many times as its count.
        # 迭代這個序列中的每一個元素(Key),改元素(Key)出現的次數,則等於他的值(Value)
        >>> c = Counter('ABCABC')
        >>> sorted(c.elements())
        ['A', 'A', 'B', 'B', 'C', 'C']

        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
        >>> product = 1
        >>> for factor in prime_factors.elements():     # loop over factors
        ...     product *= factor                       # and multiply them
        >>> product  # == 2 * 2 * 3 * 3 * 3 * 17
        1836

        註意:如果一個元素的計數被設置為0或者負數,elements()將忽略他
        Note, if an element's count has been set to zero or is a negative
        number, elements() will ignore it.

        '''
        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
        return _chain.from_iterable(_starmap(_repeat, self.iteritems()))

    # Override dict methods where necessary

    @classmethod
    def fromkeys(cls, iterable, v=None):
        """該方法還沒有實現"""
        # There is no equivalent method for counters because setting v=1
        # means that no element can have a count greater than one.
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

    def update(*args, **kwds):
        '''Like dict.update() but add counts instead of replacing them.
            像字典中的update()方法一樣,但是這裡是添加計數,而不是覆蓋它

        Source can be an iterable, a dictionary, or another Counter instance.
        源數據可以是一個迭代器,一個字典,或者是另一個Counter實例


        >>> c = Counter('which')
        >>> c.update('witch')           # add elements from another iterable  添加元素來自另一可迭代的元素
        >>> d = Counter('watch')
        >>> c.update(d)                 # add elements from another counter   添加元素來自另一個counter計數器
        >>> c['h']                      # four 'h' in which, witch, and watch
        4

        '''
        # The regular dict.update() operation makes no sense here because the
        # replace behavior results in the some of original untouched counts
        # being mixed-in with all of the other counts for a mismash that
        # doesn't have a straight-forward interpretation in most counting
        # contexts.  Instead, we implement straight-addition.  Both the inputs
        # and outputs are allowed to contain zero and negative counts.

        if not args:
            raise TypeError("descriptor 'update' of 'Counter' object "
                            "needs an argument")
        self = args[0]
        args = args[1:]
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        iterable = args[0] if args else None
        if iterable is not None:
            if isinstance(iterable, Mapping):
                if self:
                    self_get = self.get
                    for elem, count in iterable.iteritems():
                        self[elem] = self_get(elem, 0) + count
                else:
                    super(Counter, self).update(iterable) # fast path when counter is empty
            else:
                self_get = self.get
                for elem in iterable:
                    self[elem] = self_get(elem, 0) + 1
        if kwds:
            self.update(kwds)

    def subtract(*args, **kwds):
        '''Like dict.update() but subtracts counts instead of replacing them.
        Counts can be reduced below zero.  Both the inputs and outputs are
        allowed to contain zero and negative counts.

        Source can be an iterable, a dictionary, or another Counter instance.
        # 與update方法相反,這個是減

        >>> c = Counter('which')
        >>> c.subtract('witch')             # subtract elements from another iterable
        >>> c.subtract(Counter('watch'))    # subtract elements from another counter
        >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
        0
        >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
        -1

        '''
        if not args:
            raise TypeError("descriptor 'subtract' of 'Counter' object "
                            "needs an argument")
        self = args[0]
        args = args[1:]
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        iterable = args[0] if args else None
        if iterable is not None:
            self_get = self.get
            if isinstance(iterable, Mapping):
                for elem, count in iterable.items():
                    self[elem] = self_get(elem, 0) - count
            else:
                for elem in iterable:
                    self[elem] = self_get(elem, 0) - 1
        if kwds:
            self.subtract(kwds)

    def copy(self):
        'Return a shallow copy.'
        """淺拷貝"""
        return self.__class__(self)

    def __reduce__(self):
        return self.__class__, (dict(self),)

    def __delitem__(self, elem):
        'Like dict.__delitem__() but does not raise KeyError for missing values.'
        if elem in self:
            super(Counter, self).__delitem__(elem)

    def __repr__(self):
        if not self:
            return '%s()' % self.__class__.__name__
        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
        return '%s({%s})' % (self.__class__.__name__, items)

    # Multiset-style mathematical operations discussed in:
    #       Knuth TAOCP Volume II section 4.6.3 exercise 19
    #       and at http://en.wikipedia.org/wiki/Multiset
    #
    # Outputs guaranteed to only include positive counts.
    #
    # To strip negative and zero counts, add-in an empty counter:
    #       c += Counter()

    def __add__(self, other):
        '''Add counts from two counters.

        >>> Counter('abbb') + Counter('bcc')
        Counter({'b': 4, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            newcount = count + other[elem]
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count > 0:
                result[elem] = count
        return result

    def __sub__(self, other):
        ''' Subtract count, but keep only results with positive counts.

        >>> Counter('abbbc') - Counter('bccd')
        Counter({'b': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            newcount = count - other[elem]
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count < 0:
                result[elem] = 0 - count
        return result

    def __or__(self, other):
        '''Union is the maximum of value in either of the input counters.

        >>> Counter('abbb') | Counter('bcc')
        Counter({'b': 3, 'c': 2, 'a': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            other_count = other[elem]
            newcount = other_count if count < other_count else count
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count > 0:
                result[elem] = count
        return result

    def __and__(self, other):
        ''' Intersection is the minimum of corresponding counts.

        >>> Counter('abbb') & Counter('bcc')
        Counter({'b': 1})

        '''
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            other_count = other[elem]
            newcount = count if count < other_count else other_count
            if newcount > 0:
               

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 先安照路徑放好如圖。簡單使用無logo:public function qrcode(){ Vendor('phpqrcode.phpqrcode'); //生成二維碼圖片 $object = new \QRcode(); $url='http...
  • index_uploads index_uploads.php "; print_r($_FILES); echo ""; ...
  • 主要界面如下:主要代碼如下:BOOL CEnumProcessDlg::OnInitDialog(){ CDialog::OnInitDialog(); // 將“關於...”菜單項添加到系統菜單中。 // IDM_ABOUTBOX 必須在系統命令範圍內。 ASSERT((I...
  • package com.oumyye.圖片;import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import ...
  • 首先,我的博客地址是http://www.cnblogs.com/naiwenmoer/,這也是我第一篇博客,以前沒想過寫博客,現在有幸加入這個大神遍地飛的園子,還請各位大神多多指教了! c語言作為經典語言,這裡不再多說了.咱從基礎一起探討吧! 一. 定義一個整型,如果作為局部變...
  • 選擇排序演算法的思想類似於冒泡排序,每次從未排序的序列中選出最大或者是最小值,放在數組的頭部或者是尾部。只不過選擇演算法不是像冒泡演算法兩兩進行比較,而是每次迴圈未排序的數組,從中找出最大或者是最小值的索引,然後與未排序的數組的頭部或者尾部進行交換。直到最後只剩未排序數組只剩下一個數時,排序結束。java...
  • 目錄數組函數類和對象字元串操作會話控制時間和日期異常處理一、數組 1、索引數組header("Content-Type: text/html; charset=utf-8");//創建空數組$str = array();//索引數組:數組的鍵是整數的數組,並且鍵的整數順序是從0開始,依次類推。$f....
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...