今日所講知識點總結: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__ = Noneset
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: