• Python 基础第三天(set、collections、有序字典、队列、深浅拷贝、函数、lambda表达式、文件操作)


    Set集合#是一个无序且不重复的元素集合,只需关注value

    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
    #添加一个元素,如果添加set里面有的元素将会过滤掉
    s1 = set()
    s1.add(123)
    s1.add(123)
    print(s1)
    {123}
            """
            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
    #差集,两个集合中不相同的值生成新集合
    s = set((1,2,3,4))
    t = set((1,2,3,4,5))
    b = t.difference(s)#返回一个新的set包含t中有但是s中没有的元素
    print(b)
    {5}
    b = s.difference(t)#返回一个新的set包含s中有但是t中没有的元素
    print(b)
    set()
            """
            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中的所包含在参数集合中的元素
    s = set((1,2,3))
    t = set((1,2,3,4,5))
    t.difference_update(s)#返回删除set “s”中的元素的set “t”
    print(t)
    {4, 5}
            """ Remove all elements of another set from this set. """
            pass
    
        def discard(self, *args, **kwargs): # real signature unknown
    #移除
    t = set((1,2,3,4,5))
    t.discard(5)#如果在set “t”中存在元素5,则删除
    print(t)
    {1, 2, 3, 4}
            """
            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
    #取交集,生成新的集合
    s = set((1,2,3))
    t = set((1,2,3,4,5))
    a = s.intersection(t)
    b = t.intersection(s)#返回set "s"和 set “t”中共有元素
    print(a,b)
    {1, 2, 3} {1, 2, 3}
            """
            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
    #取交集,修改原集合
    s = set((1,2,3))
    t = set((1,2,3,4,5))
    s.intersection_update(t)#返回只保留含有set “t”中元素的set “s”
    print(t)
    {1, 2, 3, 4, 5}
            """ Update a set with the intersection of itself and another. """
            pass
    
        def isdisjoint(self, *args, **kwargs): # real signature unknown
    #如果没有交集,返回True
    s1 = set(["alex","eric","tony","fdsf"])
    s2 = set(["hjk","fds","alex","tony"])
    a = s1.isdisjoint(s2)
    print(a)
    False
            """ Return True if two sets have a null intersection. """
            pass
    
        def issubset(self, *args, **kwargs): # real signature unknown
    #是否是子集
    s = set((1,2,3,4))
    t = set((1,2,3,4,5))
    a = s.issubset(t)#测试是否s中的每一个元素都在t中
    print(a)
    True
    
            """ Report whether another set contains this set. """
            pass
    
        def issuperset(self, *args, **kwargs): # real signature unknown
    #是否是父集
    s = set((1,2,3,4))
    t = set((1,2,3,4,5))
    a = s.issuperset(t)#测试是否t中的每一个元素都在s中
    print(a)
    False
            """ Report whether this set contains another set. """
            pass
    
        def pop(self, *args, **kwargs): # real signature unknown
    #删除任意一个,有返回值
    s1 = set(["alex","eric","tony","fdsf"])
    s2 = set(["hjk","fds","alex","tony"])
    a = s2.pop()#随机删除一个值,并将删除的值返回
    print(a)
    print(s1,s2)
    alex
    {'tony', 'eric', 'fdsf', 'alex'} {'tony', 'fds', 'hjk'}
            """
            Remove and return an arbitrary set element.
            Raises KeyError if the set is empty.
            """
            pass
    
        def remove(self, *args, **kwargs): # real signature unknown
    #删除指定元素,无返回值
    s2 = set(["hjk","fds","alex","tony"])
    a = s2.remove("hjk")#从set “s2”中删除指定元素,无返回值;如果不存在则引发keyerror
    print(a)
    print(s1,s2)
    None
    {'tony', 'fds', 'alex'}
            """
            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
    #对称差集(取双方对象中都不重复的元素),创建新集合
    s = set((1,2,6))
    t = set((1,2,3,4,5))
    a = s.symmetric_difference(t)#返回一个新的set包含s和t中不重复的元素
    print(a)
    {3, 4, 5, 6}
            """
            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
    #差集,改变原来
    s = set((1,2,3,4))
    t = set((1,2,3,4,5))
    s.symmetric_difference_update(t)#返回含义set “t”和set “s”中有而不是两者都有的元素的set “s”
    print(s)
    {5}
    
            """ Update a set with the symmetric difference of itself and another. """
            pass
    
        def union(self, *args, **kwargs): # real signature unknown
    #并集
    s = set((1,2,3,4))
    t = set((1,2,3,4,5))
    a = s.union(t)#返回一个新的set包含s和t中的每一个元素
    print(a)
    {1, 2, 3, 4, 5}
            """
            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
    #更新
    s = set((1,2,3,4))
    t = set((1,2,3,4,5))
    t.update(s)#“t”中包含“s”中对象,则“t”返回原值
    s.update(t)#“s”中未包含“t”中对象,则s返回增加t中元素的set“
    print(t)
    {1, 2, 3, 4, 5}
    print(s)
    {1, 2, 3, 4, 5}
            """ 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

    collections系列

    计数器(Counter)#对字典进行加工

    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.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 = args
            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.
    
            >>> Counter('abcdeabcdabcaba').most_common(3)
            [('a', 5), ('b', 4), ('c', 3)]
    
            '''
            # Emulate Bag.sortedByCount from Smalltalk
            if n is None:
                return sorted(self.items(), key=_itemgetter(1), reverse=True)
            return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
    
        def elements(self):
            '''Iterator over elements repeating each as many times as its count.
    #列出所有元素
            >>> 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
            1836
    
            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.items()))
    
        # 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):
    #更新数据
    >>> a = collections.Counter(["11","22","33"])
    a.update(["alex"])
    >>> print(a)
    Counter({'11': 1, '33': 1, '22': 1, 'alex': 1})
            '''Like dict.update() but add counts instead of replacing them.
    
            Source can be an iterable, a dictionary, or another Counter instance.
    
            >>> c = Counter('which')
            >>> c.update('witch')           # add elements from another iterable
            >>> d = Counter('watch')
            >>> c.update(d)                 # add elements from another 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 = args
            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.items():
                            self[elem] = count + self_get(elem, 0)
                    else:
                        super(Counter, self).update(iterable) # fast path when counter is empty
                else:
                    _count_elements(self, iterable)
            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.
    
            >>> 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 = args
            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().__delitem__(elem)
    
        def __repr__(self):
            if not self:
                return '%s()' % self.__class__.__name__
            try:
                items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
                return '%s({%s})' % (self.__class__.__name__, items)
            except TypeError:
                # handle case where values are not orderable
                return '{0}({1!r})'.format(self.__class__.__name__, dict(self))
    
        # 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:
                    result[elem] = newcount
            return result
    
        def __pos__(self):
            'Adds an empty counter, effectively stripping negative and zero counts'
            result = Counter()
            for elem, count in self.items():
                if count > 0:
                    result[elem] = count
            return result
    
        def __neg__(self):
            '''Subtracts from an empty counter.  Strips positive and zero counts,
            and flips the sign on negative counts.
    
            '''
            result = Counter()
            for elem, count in self.items():
                if count < 0:
                    result[elem] = 0 - count
            return result
    
        def _keep_positive(self):
            '''Internal method to strip elements with a negative or zero count'''
            nonpositive = [elem for elem, count in self.items() if not count > 0]
            for elem in nonpositive:
                del self[elem]
            return self
    
        def __iadd__(self, other):
            '''Inplace add from another counter, keeping only positive counts.
    
            >>> c = Counter('abbb')
            >>> c += Counter('bcc')
            >>> c
            Counter({'b': 4, 'c': 2, 'a': 1})
    
            '''
            for elem, count in other.items():
                self[elem] += count
            return self._keep_positive()
    
        def __isub__(self, other):
            '''Inplace subtract counter, but keep only results with positive counts.
    
            >>> c = Counter('abbbc')
            >>> c -= Counter('bccd')
            >>> c
            Counter({'b': 2, 'a': 1})
    
            '''
            for elem, count in other.items():
                self[elem] -= count
            return self._keep_positive()
    
        def __ior__(self, other):
            '''Inplace union is the maximum of value from either counter.
    
            >>> c = Counter('abbb')
            >>> c |= Counter('bcc')
            >>> c
            Counter({'b': 3, 'c': 2, 'a': 1})
    
            '''
            for elem, other_count in other.items():
                count = self[elem]
                if other_count > count:
                    self[elem] = other_count
            return self._keep_positive()
    
        def __iand__(self, other):
            '''Inplace intersection is the minimum of corresponding counts.
    
            >>> c = Counter('abbb')
            >>> c &= Counter('bcc')
            >>> c
            Counter({'b': 1})
    
            '''
            for elem, count in self.items():
                other_count = other[elem]
                if other_count < count:
                    self[elem] = other_count
            return self._keep_positive()

    有序字典(OrderedDict

    class OrderedDict(dict):
        """ Dictionary that remembers insertion order """
        def clear(self): # real signature unknown; restored from __doc__
            """ od.clear() -> None.  Remove all items from od. """
            pass
    
        def copy(self): # real signature unknown; restored from __doc__
            """ od.copy() -> a shallow copy of od """
            pass
    
        @classmethod
        def fromkeys(cls, S, v=None): # real signature unknown; restored from __doc__
            """
            OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
                    If not specified, the value defaults to None.
            """
            pass
    
        def items(self, *args, **kwargs): # real signature unknown
            pass
    
        def keys(self, *args, **kwargs): # real signature unknown
            pass
    
        def move_to_end(self, *args, **kwargs): # real signature unknown
    #指定一个值放到最后
            """
            Move an existing element to the end (or beginning if last==False).
            
                    Raises KeyError if the element does not exist.
                    When last=True, acts like a fast version of self[key]=self.pop(key).
            """
            pass
    
        def pop(self, k, d=None): # real signature unknown; restored from __doc__
            """
            od.pop(k[,d]) -> v, remove specified key and return the corresponding
                    value.  If key is not found, d is returned if given, otherwise KeyError
                    is raised.
            """
            pass
    
        def popitem(self): # real signature unknown; restored from __doc__
            """
            od.popitem() -> (k, v), return and remove a (key, value) pair.
                    Pairs are returned in LIFO order if last is true or FIFO order if false.
            """
            pass
    
        def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
            """ od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od """
            pass
    
        def update(self, *args, **kwargs): # real signature unknown
            pass
    
        def values(self, *args, **kwargs): # real signature unknown
            pass
    
        def __delitem__(self, *args, **kwargs): # real signature unknown
            """ Delete self[key]. """
            pass
    
        def __eq__(self, *args, **kwargs): # real signature unknown
            """ Return self==value. """
            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 __init__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __iter__(self, *args, **kwargs): # real signature unknown
            """ Implement iter(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 __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 __reversed__(self): # real signature unknown; restored from __doc__
            """ od.__reversed__() <==> reversed(od) """
            pass
    
        def __setitem__(self, *args, **kwargs): # real signature unknown
            """ Set self[key] to value. """
            pass
    
        def __sizeof__(self, *args, **kwargs): # real signature unknown
            pass
    
        __dict__ = None # (!) real value is ''
        __hash__ = None

    默认字典(defaultdict

    #!/usr/bin/env python3
    import collections
    li = [11,22,33,44,55,66,77,88,99]
    my_dict = collections.defaultdict(list)#通过默认字典,设置my_dict为空列表
    for i in li:
        if i >66:
            my_dict["k1"].append(i)
        else:
            my_dict["k2"].append(i)
    print(my_dict["k1"],my_dict["k2"])
    [77, 88, 99] [11, 22, 33, 44, 55, 66]

    可命名元组(namedtuple

    #!/usr/bin/env python3
    import collections
    MytupleClass = collections.namedtuple("MytupleClass",["x","y","z"])#通过自定义类创建别名
    a = MytupleClass(11,22,33)#通过自定义类给定元素赋值给“a”
    print(a.x,a.y,a.z)#打印出对应别名的值
    11 22 33

    双向队列(deque

    class deque(object):
        """
        deque([iterable[, maxlen]]) --> deque object
        
        A list-like sequence optimized for data accesses near its endpoints.
        """
        def append(self, *args, **kwargs): # real signature unknown
    #添加元素
            """ Add an element to the right side of the deque. """
            pass
    
        def appendleft(self, *args, **kwargs): # real signature unknown
    #在左边添加元素
            """ Add an element to the left side of the deque. """
            pass
    
        def clear(self, *args, **kwargs): # real signature unknown
    #清空元素
            """ Remove all elements from the deque. """
            pass
    
        def copy(self, *args, **kwargs): # real signature unknown
            """ Return a shallow copy of a deque. """
            pass
    
        def count(self, value): # real signature unknown; restored from __doc__
    #统计元素出现的次数
            """ D.count(value) -> integer -- return number of occurrences of value """
            return 0
    
        def extend(self, *args, **kwargs): # real signature unknown
    #扩展(添加多个数据)
            """ Extend the right side of the deque with elements from the iterable """
            pass
    
        def extendleft(self, *args, **kwargs): # real signature unknown
    #在左边扩展(添加多个数据)
            """ Extend the left side of the deque with elements from the iterable """
            pass
    
        def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
    #索引
            """
            D.index(value, [start, [stop]]) -> integer -- return first index of value.
            Raises ValueError if the value is not present.
            """
            return 0
    
        def insert(self, index, p_object): # real signature unknown; restored from __doc__
    #插入
            """ D.insert(index, object) -- insert object before index """
            pass
    
        def pop(self, *args, **kwargs): # real signature unknown
    #移除并拿到
            """ Remove and return the rightmost element. """
            pass
    
        def popleft(self, *args, **kwargs): # real signature unknown
    #从左边移除并拿到
            """ Remove and return the leftmost element. """
            pass
    
        def remove(self, value): # real signature unknown; restored from __doc__
    #删除指定值
            """ D.remove(value) -- remove first occurrence of value. """
            pass
    
        def reverse(self): # real signature unknown; restored from __doc__
    #反转
            """ D.reverse() -- reverse *IN PLACE* """
            pass
    
        def rotate(self, *args, **kwargs): # real signature unknown
    #旋转
    d = collections.deque(["1","10","1","a","f","dg"])
    print(d)
    d.rotate(3)#按照数字进行旋转,每次拿最后一个元素放到最前面
    print(d)
    deque(['1', '10', '1', 'a', 'f', 'dg'])
    deque(['a', 'f', 'dg', '1', '10', '1'])
            """ Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left. """
            pass
    
        def __add__(self, *args, **kwargs): # real signature unknown
            """ Return self+value. """
            pass
    
        def __bool__(self, *args, **kwargs): # real signature unknown
            """ self != 0 """
            pass
    
        def __contains__(self, *args, **kwargs): # real signature unknown
            """ Return key in self. """
            pass
    
        def __copy__(self, *args, **kwargs): # real signature unknown
            """ Return a shallow copy of a deque. """
            pass
    
        def __delitem__(self, *args, **kwargs): # real signature unknown
            """ Delete self[key]. """
            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 __getitem__(self, *args, **kwargs): # real signature unknown
            """ Return self[key]. """
            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 __iadd__(self, *args, **kwargs): # real signature unknown
            """ Implement self+=value. """
            pass
    
        def __imul__(self, *args, **kwargs): # real signature unknown
            """ Implement self*=value. """
            pass
    
        def __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__
            """
            deque([iterable[, maxlen]]) --> deque object
            
            A list-like sequence optimized for data accesses near its endpoints.
            # (copied from class doc)
            """
            pass
    
        def __iter__(self, *args, **kwargs): # real signature unknown
            """ Implement iter(self). """
            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
    
        def __mul__(self, *args, **kwargs): # real signature unknown
            """ Return self*value.n """
            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 __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 __reversed__(self): # real signature unknown; restored from __doc__
            """ D.__reversed__() -- return a reverse iterator over the deque """
            pass
    
        def __rmul__(self, *args, **kwargs): # real signature unknown
            """ Return self*value. """
            pass
    
        def __setitem__(self, *args, **kwargs): # real signature unknown
            """ Set self[key] to value. """
            pass
    
        def __sizeof__(self): # real signature unknown; restored from __doc__
            """ D.__sizeof__() -- size of D in memory, in bytes """
            pass
    
        maxlen = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """maximum size of a deque or None if unbounded"""
    
    
        __hash__ = None

    单向队列

    #!/usr/bin/env python3
    import queue
    q = queue.Queue()#单向队列
    q.put("123","fds")#添加一条
    q.put("45")#添加一条
    print(q.qsize())#统计队列中有多少数据
    print(q.get())#取出一条数据(采用先进先出原则)
    class Queue:
        '''Create a queue object with a given maximum size.
    
        If maxsize is <= 0, the queue size is infinite.
        '''
    
        def __init__(self, maxsize=0):
            self.maxsize = maxsize
            self._init(maxsize)
    
            # mutex must be held whenever the queue is mutating.  All methods
            # that acquire mutex must release it before returning.  mutex
            # is shared between the three conditions, so acquiring and
            # releasing the conditions also acquires and releases mutex.
            self.mutex = threading.Lock()
    
            # Notify not_empty whenever an item is added to the queue; a
            # thread waiting to get is notified then.
            self.not_empty = threading.Condition(self.mutex)
    
            # Notify not_full whenever an item is removed from the queue;
            # a thread waiting to put is notified then.
            self.not_full = threading.Condition(self.mutex)
    
            # Notify all_tasks_done whenever the number of unfinished tasks
            # drops to zero; thread waiting to join() is notified to resume
            self.all_tasks_done = threading.Condition(self.mutex)
            self.unfinished_tasks = 0
    
        def task_done(self):
            '''Indicate that a formerly enqueued task is complete.
    
            Used by Queue consumer threads.  For each get() used to fetch a task,
            a subsequent call to task_done() tells the queue that the processing
            on the task is complete.
    
            If a join() is currently blocking, it will resume when all items
            have been processed (meaning that a task_done() call was received
            for every item that had been put() into the queue).
    
            Raises a ValueError if called more times than there were items
            placed in the queue.
            '''
            with self.all_tasks_done:
                unfinished = self.unfinished_tasks - 1
                if unfinished <= 0:
                    if unfinished < 0:
                        raise ValueError('task_done() called too many times')
                    self.all_tasks_done.notify_all()
                self.unfinished_tasks = unfinished
    
        def join(self):
            '''Blocks until all items in the Queue have been gotten and processed.
    
            The count of unfinished tasks goes up whenever an item is added to the
            queue. The count goes down whenever a consumer thread calls task_done()
            to indicate the item was retrieved and all work on it is complete.
    
            When the count of unfinished tasks drops to zero, join() unblocks.
            '''
            with self.all_tasks_done:
                while self.unfinished_tasks:
                    self.all_tasks_done.wait()
    
        def qsize(self):
    #查看队列中元素的个数
            '''Return the approximate size of the queue (not reliable!).'''
            with self.mutex:
                return self._qsize()
    
        def empty(self):
    #和clear一样
            '''Return True if the queue is empty, False otherwise (not reliable!).
    
            This method is likely to be removed at some point.  Use qsize() == 0
            as a direct substitute, but be aware that either approach risks a race
            condition where a queue can grow before the result of empty() or
            qsize() can be used.
    
            To create code that needs to wait for all queued tasks to be
            completed, the preferred technique is to use the join() method.
            '''
            with self.mutex:
                return not self._qsize()
    
        def full(self):
    #是否填满
            '''Return True if the queue is full, False otherwise (not reliable!).
    
            This method is likely to be removed at some point.  Use qsize() >= n
            as a direct substitute, but be aware that either approach risks a race
            condition where a queue can shrink before the result of full() or
            qsize() can be used.
            '''
            with self.mutex:
                return 0 < self.maxsize <= self._qsize()
    
        def put(self, item, block=True, timeout=None):
    #插入数据
            '''Put an item into the queue.
    
            If optional args 'block' is true and 'timeout' is None (the default),
            block if necessary until a free slot is available. If 'timeout' is
            a non-negative number, it blocks at most 'timeout' seconds and raises
            the Full exception if no free slot was available within that time.
            Otherwise ('block' is false), put an item on the queue if a free slot
            is immediately available, else raise the Full exception ('timeout'
            is ignored in that case).
            '''
            with self.not_full:
                if self.maxsize > 0:
                    if not block:
                        if self._qsize() >= self.maxsize:
                            raise Full
                    elif timeout is None:
                        while self._qsize() >= self.maxsize:
                            self.not_full.wait()
                    elif timeout < 0:
                        raise ValueError("'timeout' must be a non-negative number")
                    else:
                        endtime = time() + timeout
                        while self._qsize() >= self.maxsize:
                            remaining = endtime - time()
                            if remaining <= 0.0:
                                raise Full
                            self.not_full.wait(remaining)
                self._put(item)
                self.unfinished_tasks += 1
                self.not_empty.notify()
    
        def get(self, block=True, timeout=None):
    #取数据
            '''Remove and return an item from the queue.
    
            If optional args 'block' is true and 'timeout' is None (the default),
            block if necessary until an item is available. If 'timeout' is
            a non-negative number, it blocks at most 'timeout' seconds and raises
            the Empty exception if no item was available within that time.
            Otherwise ('block' is false), return an item if one is immediately
            available, else raise the Empty exception ('timeout' is ignored
            in that case).
            '''
            with self.not_empty:
                if not block:
                    if not self._qsize():
                        raise Empty
                elif timeout is None:
                    while not self._qsize():
                        self.not_empty.wait()
                elif timeout < 0:
                    raise ValueError("'timeout' must be a non-negative number")
                else:
                    endtime = time() + timeout
                    while not self._qsize():
                        remaining = endtime - time()
                        if remaining <= 0.0:
                            raise Empty
                        self.not_empty.wait(remaining)
                item = self._get()
                self.not_full.notify()
                return item
    
        def put_nowait(self, item):
            '''Put an item into the queue without blocking.
    
            Only enqueue the item if a free slot is immediately available.
            Otherwise raise the Full exception.
            '''
            return self.put(item, block=False)
    
        def get_nowait(self):
            '''Remove and return an item from the queue without blocking.
    
            Only get an item if one is immediately available. Otherwise
            raise the Empty exception.
            '''
            return self.get(block=False)
    
        # Override these methods to implement other queue organizations
        # (e.g. stack or priority queue).
        # These will only be called with appropriate locks held
    
        # Initialize the queue representation
        def _init(self, maxsize):
            self.queue = deque()
    
        def _qsize(self):
            return len(self.queue)
    
        # Put a new item in the queue
        def _put(self, item):
            self.queue.append(item)
    
        # Get an item from the queue
        def _get(self):
            return self.queue.popleft()

    浅拷贝

    dic = {"cpu":[80],"mom":[80],"disk":[80]}
    print("old",dic)
    new_dic = copy.copy(dic) #浅拷贝,会改变原数据
    new_dic["cpu"][0] = 50
    print(dic)
    print(new_dic)

    深拷贝

    dic = {"cpu":80,"mom":80,"disk":80}
    print("old",dic)
    new_dic = copy.deepcopy(dic)#深拷贝则修改你要改的值
    new_dic["cpu"] = 50
    print(dic)
    print(new_dic)

    函数

    def show():#def是定义函数的关键字,函数名后必须更括号
        print("123")
        return"ss" #返回值,不写return返回None
    a = show()#函数名加扩号,表示执行该函数,可将返回值赋值给变量
    print(a)
    123
    ss
    #一个参数
    def show(a):#形参
        print(a)
    show(123)#实参,把参数赋值给a
    123
    #多个参数
    def show(a,b,c):#可指定多形参
        print(a,b,c)
    show(123,456,789)#实参数量必须和形参一致(一一对应)
    123 456 789
    def show(args):
        print(args)
    show([123,456,789])
    [123, 456, 789]
    #默认参数
    def show(a,b=123):#默认参数须先赋值,只能写到最后(a后面,并且后面也不能跟形参)
        print(a,b)
    show(123,456)
    123 456
    #指定参数
    def show(a,b,c):
        print(a,b,c)
    show(c=789,a=123,b=456,)
    123 456 789
    #动态参数
    def show(*args):#单星转成元组
        print(args,type(args))
    show([123,456,789])
    ([123, 456, 789],) <class 'tuple'>
    def show(**kwargs):#双星转成字典
        print(kwargs,type(kwargs))
    show(a=123,b=456)
    {'b': 456, 'a': 123} <class 'dict'>
    def show(*a,**b):#混合模式下,必须单星在前
        print(a,type(a))
        print(b,type(b))
    show(123,456,abc = 123,cde = 456)#不能混传,如(abc = 123,123)必须根据星来使用
    (123, 456) <class 'tuple'>
    {'cde': 456, 'abc': 123} <class 'dict'>
    
    def show(*a,**b):
        print(a,type(a))
        print(b,type(b))
    l =(123,456)
    d ={'abc':123,'cde':456}
    show(*l,**d)#把值传到指定位置
    (123, 456) <class 'tuple'>
    {'abc': 123, 'cde': 456} <class 'dict'>
    
    #字符格式化
    c = ["name","abc"]
    d = {"a":"name","b":"abc"}
    s = "{0} is {1}".format(*c)
    s1 = "{a} is {b}".format(**d)
    print(s,s1)

    Lambda表达式

    def func(a,b):
       return a*b
    ret = func(4,5)
    print(ret)
    #lambda表达式,同以上函数
    func = lambda a,b: a*b
    ret = func(4,5)
    print(ret)

    内置函数#只写了部分

    all()#传入的序列所有的值都真,才为真
    all(["",[],(),{},None])#为假
    
    any()#只有一个真都为真
    any(["",[],(),{},None,1,])#只有一个真都为真
    
    ascii(8) 等同 (int.__repr__(8))
    
    bin()#二进制
    
    bytearray("方法",encoding="utf-8")#转成字节数组
    
    bytes("方法",encoding="utf-8")#转成字符
    
    callable()#是否可执行
    
    chr()#数字转ascii字符
    chr(65)
    
    ord()#ascii转数字
    ord("A")
    
    enumerate()#生成序列
    li = ["a","b","c"]
    for i,item in enumerate(li,1):
       print(i,item)
    
    eval("6*8")#将字符串运算转换为数字运算

    文件操作

    文件句柄 = open("文件路径","模式")

    打开文件的模式有:

    r,只读模式(默认)

    w,只写模式(不可读,不存在创建文件,存在删除内容)

    a,追加模式(可读,不存在创建文件,存在追加内容)

    “+”表示可以同时读写

      r+,可读写文件(可读,可写,可追加)

      w+,写读

      a+,同a

    “U”表示在读取时,可以将\r \n \r\n自动转换成\n(与r或r+模式同使用)

      ru

    r+U

    “b”表示处理二进制文件(如:FTP发送上传ISO镜像文件,Linux可忽略,Windows处理二进制文件时需标注)

      rb

      wb

      ab

  • 相关阅读:
    《设计模式
    JConsole监控远程Tomcat服务器
    Linux下Nginx+tomcat应用系统性能优化
    nginx 解决400 bad request 的方法
    lvs、haproxy、nginx 负载均衡的比较分析
    三种LVS负载均衡技术的优缺点----负载均衡调度算法
    LVS集群的体系结构
    LVS--什么是LVS?
    七、Nginx学习笔记七Nginx的Web缓存服务
    六、Nginx 防盗链
  • 原文地址:https://www.cnblogs.com/pathping/p/5177147.html
Copyright © 2020-2023  润新知