标签:
今日所讲知识点总结:
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
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: result[elem] = newcount return result
标签:
原文地址:http://www.cnblogs.com/CongZhang/p/5137919.html