python数据类型之 set

set是一个无序且不重复的元素集合

  1 class set(object):
  2     """
  3     set() -> new empty set object
  4     set(iterable) -> new set object
  5     
  6     Build an unordered collection of unique elements.
  7     打造唯一元素的无序集合
  8     """
  9     def add(self, *args, **kwargs): # real signature unknown
 10         """
 11         Add an element to a set.
 12         增加一个元素到集合
 13         eg:
 14             s1 = set([1,2,3])
 15                     s1.add(4)
 16         
 17         This has no effect if the element is already present.
 18         
 19         """
 20         pass
 21 
 22     def clear(self, *args, **kwargs): # real signature unknown
 23         """ Remove all elements from this set. """
 24         移除集合中所有元素
 25         pass
 26 
 27     def copy(self, *args, **kwargs): # real signature unknown
 28         """ Return a shallow copy of a set. """
 29         浅拷贝
 30         pass
 31 
 32     def difference(self, *args, **kwargs): # real signature unknown
 33         """
 34         Return the difference of two or more sets as a new set.
 35         返回两个或多个集合的不同为一个新的集合
 36         eg:
 37                     old_dict = set([1,2,3,4,5,6,7])
 38                             # cmdb 新汇报的数据
 39                             new_dict = set([5,6,7,8,9])
 40                             now_dict = set([5,6,7,1,0])
 41                             print(old_dict.difference(new_dict,now_dict))
 42         (i.e. all elements that are in this set but not the others.)
 43         """
 44         pass
 45 
 46     def difference_update(self, *args, **kwargs): # real signature unknown
 47         """ Remove all elements of another set from this set. 
 48         从当前集合中移除另一集合的所有元素,当前集合被改变
 49         eg:
 50                 old_dict = set([1,2,3,4,5,6,7])
 51                         # cmdb 新汇报的数据
 52                         new_dict = set([5,6,7,8,9])
 53                         old_dict.difference_update(new_dict)
 54                         print(old_dict)
 55         """
 56         pass
 57 
 58     def discard(self, *args, **kwargs): # real signature unknown
 59         """
 60         Remove an element from a set if it is a member.
 61         移除一个集合的中一个元素,如果没有则什么都不做
 62         If the element is not a member, do nothing.
 63         """
 64         pass
 65 
 66     def intersection(self, *args, **kwargs): # real signature unknown
 67         """
 68         Return the intersection of two sets as a new set.
 69         返回两个集合的交集为一个新的集合
 70         (i.e. all elements that are in both sets.)
 71         """
 72         pass
 73 
 74     def intersection_update(self, *args, **kwargs): # real signature unknown
 75         """ Update a set with the intersection of itself and another. 
 76         更新一个集合,使用它和另一集合的交集
 77         eg:
 78                 old_dict = set([1,2,3,4,5])
 79                         new_dict  = set([4,5,6,7,8])
 80                         print(old_dict)
 81         """
 82         pass
 83 
 84     def isdisjoint(self, *args, **kwargs): # real signature unknown
 85         """ Return True if two sets have a null intersection. 
 86         如果两个集合没有交集则返回真
 87         """
 88         pass
 89 
 90     def issubset(self, *args, **kwargs): # real signature unknown
 91         """ Report whether another set contains this set. 
 92         如果此集合包含在另一集合中,则返回真
 93         eg:
 94                 old_dict = set([1,2,3,4,5,6,7,8])
 95                         # cmdb 新汇报的数据
 96                         new_dict = set([5,6,7,8])
 97                         print(new_dict.issubset(old_dict))
 98         """
 99         pass
100 
101     def issuperset(self, *args, **kwargs): # real signature unknown
102         """ Report whether this set contains another set. 
103         此集合包含另一集合则返回真
104                 old_dict = set([1,2,3,4,5,6,7,8])
105                         # cmdb 新汇报的数据
106                         new_dict = set([5,6,7,8])
107                         print(old_dict.issuperset(new_dict))
108         """
109         pass
110 
111     def pop(self, *args, **kwargs): # real signature unknown
112         """
113         Remove and return an arbitrary set element.
114         Raises KeyError if the set is empty.
115         随机移除集合中的一个元素
116         eg:
117                 old_dict = set([1,2,3,4,5,6,7,8])
118                         print(old_dict.pop())
119         """
120         pass
121 
122     def remove(self, *args, **kwargs): # real signature unknown
123         """
124         Remove an element from a set; it must be a member.
125         移出集合中的一个元素,如果元素不存在则报错
126         If the element is not a member, raise a KeyError.
127         """
128         pass
129 
130     def symmetric_difference(self, *args, **kwargs): # real signature unknown
131         """
132         Return the symmetric difference of two sets as a new set.
133         (i.e. all elements that are in exactly one of the sets.)
134         """
135         pass
136 
137     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
138         """ Update a set with the symmetric difference of itself and another. """
139         pass
140 
141     def union(self, *args, **kwargs): # real signature unknown
142         """
143         Return the union of sets as a new set.
144         返回两个集合的合集为一个新的集合
145         (i.e. all elements that are in either set.)
146         """
147         pass
148 
149     def update(self, *args, **kwargs): # real signature unknown
150         """ Update a set with the union of itself and others.
151         更新此集合,使用此集合与另一集合的合集
152          """
153         pass
154 
155     def __and__(self, *args, **kwargs): # real signature unknown
156         """ Return self&value. """
157         pass
158 
159     def __contains__(self, y): # real signature unknown; restored from __doc__
160         """ x.__contains__(y) <==> y in x. """
161         pass
162 
163     def __eq__(self, *args, **kwargs): # real signature unknown
164         """ Return self==value. """
165         pass
166 
167     def __getattribute__(self, *args, **kwargs): # real signature unknown
168         """ Return getattr(self, name). """
169         pass
170 
171     def __ge__(self, *args, **kwargs): # real signature unknown
172         """
173         __ge__=($self, value, /)
174         --
175         
176         Return self>=value.
177         """
178         pass
179 
180     def __gt__(self, *args, **kwargs): # real signature unknown
181         """ Return self>value. """
182         pass
183 
184     def __iand__(self, *args, **kwargs): # real signature unknown
185         """ Return self&=value. """
186         pass
187 
188     def __init__(self, seq=()): # known special case of set.__init__
189         """
190         set() -> new empty set object
191         set(iterable) -> new set object
192         
193         Build an unordered collection of unique elements.
194         # (copied from class doc)
195         """
196         pass
197 
198     def __ior__(self, *args, **kwargs): # real signature unknown
199         """ Return self|=value. """
200         pass
201 
202     def __isub__(self, *args, **kwargs): # real signature unknown
203         """ Return self-=value. """
204         pass
205 
206     def __iter__(self, *args, **kwargs): # real signature unknown
207         """ Implement iter(self). """
208         pass
209 
210     def __ixor__(self, *args, **kwargs): # real signature unknown
211         """ Return self^=value. """
212         pass
213 
214     def __len__(self, *args, **kwargs): # real signature unknown
215         """ Return len(self). """
216         pass
217 
218     def __le__(self, *args, **kwargs): # real signature unknown
219         """ Return self<=value. """
220         pass
221 
222     def __lt__(self, *args, **kwargs): # real signature unknown
223         """ Return self<value. """
224         pass
225 
226     @staticmethod # known case of __new__
227     def __new__(*args, **kwargs): # real signature unknown
228         """ Create and return a new object.  See help(type) for accurate signature. """
229         pass
230 
231     def __ne__(self, *args, **kwargs): # real signature unknown
232         """ Return self!=value. """
233         pass
234 
235     def __or__(self, *args, **kwargs): # real signature unknown
236         """ Return self|value. """
237         pass
238 
239     def __rand__(self, *args, **kwargs): # real signature unknown
240         """ Return value&self. """
241         pass
242 
243     def __reduce__(self, *args, **kwargs): # real signature unknown
244         """ Return state information for pickling. """
245         pass
246 
247     def __repr__(self, *args, **kwargs): # real signature unknown
248         """ Return repr(self). """
249         pass
250 
251     def __ror__(self, *args, **kwargs): # real signature unknown
252         """ Return value|self. """
253         pass
254 
255     def __rsub__(self, *args, **kwargs): # real signature unknown
256         """ Return value-self. """
257         pass
258 
259     def __rxor__(self, *args, **kwargs): # real signature unknown
260         """ Return value^self. """
261         pass
262 
263     def __sizeof__(self): # real signature unknown; restored from __doc__
264         """ S.__sizeof__() -> size of S in memory, in bytes """
265         pass
266 
267     def __sub__(self, *args, **kwargs): # real signature unknown
268         """ Return self-value. """
269         pass
270 
271     def __xor__(self, *args, **kwargs): # real signature unknown
272         """ Return self^value. """
273         pass
View Code

collections系列 

一、计数器(Counter)

拥有字典的所有功能,另加自己的功能

from collections import Counter

  1 class Counter(dict):
  2     '''Dict subclass for counting hashable items.  Sometimes called a bag
  3     or multiset.  Elements are stored as dictionary keys and their counts
  4     are stored as dictionary values.
  5         统计元素的个数,存储在字典中,元素为键,个数为值
  6     >>> c = Counter('abcdeabcdabcaba')  # count elements from a string
  7         生成一个计数器,以字典形式存储
  8     >>> c.most_common(3)                # three most common elements
  9     [('a', 5), ('b', 4), ('c', 3)]
 10     出现3次以上的元素
 11     >>> sorted(c)                       # list all unique elements
 12     ['a', 'b', 'c', 'd', 'e']
 13     列出唯一元素值
 14     >>> ''.join(sorted(c.elements()))   # list elements with repetitions
 15     'aaaaabbbbcccdde'
 16     列出所有元素,包括重复值
 17     >>> sum(c.values())                 # total of all counts
 18     15
 19     对所有元素出现的次数求和
 20     >>> c['a']                          # count of letter 'a'
 21     5
 22     统计a出现的次数
 23     >>> for elem in 'shazam':           # update counts from an iterable
 24     ...     c[elem] += 1                # by adding 1 to each element's count
 25     >>> c['a']                          # now there are seven 'a'
 26     7
 27     从一个迭代中更新元素重复的次数,通过加1来改变每个元素重复的次数
 28     >>> del c['b']                      # remove all 'b'
 29     >>> c['b']                          # now there are zero 'b'
 30     0
 31     删除计数器中所有的b元素的统计
 32     >>> d = Counter('simsalabim')       # make another counter
 33     创建一个新的生成器
 34     >>> c.update(d)                     # add in the second counter
 35     >>> c['a']                          # now there are nine 'a'
 36     9
 37     将d计数器合并到c生成器
 38     >>> c.clear()                       # empty the counter
 39     >>> c
 40     Counter()
 41     清空c计数器
 42     Note:  If a count is set to zero or reduced to zero, it will remain
 43     in the counter until the entry is deleted or the counter is cleared:
 44         如果一个元素的计数被设置为0或者减少到0,则此元素在计数器中仍存在,只是为0而已,
 45         除非使用delete或clear彻底删除
 46     >>> c = Counter('aaabbc')
 47     >>> c['b'] -= 2                     # reduce the count of 'b' by two
 48     >>> c.most_common()                 # 'b' is still in, but its count is zero
 49     [('a', 3), ('c', 1), ('b', 0)]
 50 
 51     '''
 52     # References:
 53     #   http://en.wikipedia.org/wiki/Multiset
 54     #   http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
 55     #   http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
 56     #   http://code.activestate.com/recipes/259174/
 57     #   Knuth, TAOCP Vol. II section 4.6.3
 58 
 59     def __init__(self, iterable=None, **kwds):
 60         '''Create a new, empty Counter object.  And if given, count elements
 61         from an input iterable.  Or, initialize the count from another mapping
 62         of elements to their counts.
 63 
 64         >>> c = Counter()                           # a new, empty counter
 65         >>> c = Counter('gallahad')                 # a new counter from an iterable
 66         >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
 67         >>> c = Counter(a=4, b=2)                   # a new counter from keyword args
 68 
 69         '''
 70         super().__init__()
 71         self.update(iterable, **kwds)
 72 
 73     def __missing__(self, key):
 74         'The count of elements not in the Counter is zero.'
 75         # Needed so that self[missing_item] does not raise KeyError
 76         return 0
 77 
 78     def most_common(self, n=None):
 79         '''List the n most common elements and their counts from the most
 80         common to the least.  If n is None, then list all element counts.
 81 
 82         >>> Counter('abcdeabcdabcaba').most_common(3)
 83         [('a', 5), ('b', 4), ('c', 3)]
 84 
 85         '''
 86         # Emulate Bag.sortedByCount from Smalltalk
 87         if n is None:
 88             return sorted(self.items(), key=_itemgetter(1), reverse=True)
 89         return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
 90 
 91     def elements(self):
 92         '''Iterator over elements repeating each as many times as its count.
 93 
 94         >>> c = Counter('ABCABC')
 95         >>> sorted(c.elements())
 96         ['A', 'A', 'B', 'B', 'C', 'C']
 97 
 98         # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
 99         >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
100         >>> product = 1
101         >>> for factor in prime_factors.elements():     # loop over factors
102         ...     product *= factor                       # and multiply them
103         >>> product
104         1836
105 
106         Note, if an element's count has been set to zero or is a negative
107         number, elements() will ignore it.
108                 如果元素的数量已经置为0或者负数,则做运算时被忽略
109         '''
110         # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
111         return _chain.from_iterable(_starmap(_repeat, self.items()))
112     
113     # Override dict methods where necessary
114 
115     @classmethod
116     def fromkeys(cls, iterable, v=None):
117         # There is no equivalent method for counters because setting v=1
118         # means that no element can have a count greater than one.
119         raise NotImplementedError(
120             'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')
121 
122     def update(self, iterable=None, **kwds):
123         '''Like dict.update() but add counts instead of replacing them.
124                 更新,相加:类似dict.update(),但不是替换而是增加计数
125         Source can be an iterable, a dictionary, or another Counter instance.
126                 
127         >>> c = Counter('which')
128         >>> c.update('witch')           # add elements from another iterable
129         >>> d = Counter('watch')
130         >>> c.update(d)                 # add elements from another counter
131         >>> c['h']                      # four 'h' in which, witch, and watch
132         4
133 
134         '''
135         # The regular dict.update() operation makes no sense here because the
136         # replace behavior results in the some of original untouched counts
137         # being mixed-in with all of the other counts for a mismash that
138         # doesn't have a straight-forward interpretation in most counting
139         # contexts.  Instead, we implement straight-addition.  Both the inputs
140         # and outputs are allowed to contain zero and negative counts.
141 
142         if iterable is not None:
143             if isinstance(iterable, Mapping):
144                 if self:
145                     self_get = self.get
146                     for elem, count in iterable.items():
147                         self[elem] = count + self_get(elem, 0)
148                 else:
149                     super().update(iterable) # fast path when counter is empty
150             else:
151                 _count_elements(self, iterable)
152         if kwds:
153             self.update(kwds)
154 
155     def subtract(self, iterable=None, **kwds):
156         '''Like dict.update() but subtracts counts instead of replacing them.
157         Counts can be reduced below zero.  Both the inputs and outputs are
158         allowed to contain zero and negative counts.
159                 相减:类似于dict.update(),减去元素的个数统计,而不是替换他们
160         Source can be an iterable, a dictionary, or another Counter instance.
161 
162         >>> c = Counter('which')
163         >>> c.subtract('witch')             # subtract elements from another iterable
164         >>> c.subtract(Counter('watch'))    # subtract elements from another counter
165         >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
166         0
167         >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
168         -1
169 
170         '''
171         if iterable is not None:
172             self_get = self.get
173             if isinstance(iterable, Mapping):
174                 for elem, count in iterable.items():
175                     self[elem] = self_get(elem, 0) - count
176             else:
177                 for elem in iterable:
178                     self[elem] = self_get(elem, 0) - 1
179         if kwds:
180             self.subtract(kwds)
181 
182     def copy(self):
183         'Return a shallow copy.'
184         return self.__class__(self)
185 
186     def __reduce__(self):
187         return self.__class__, (dict(self),)
188 
189     def __delitem__(self, elem):
190         'Like dict.__delitem__() but does not raise KeyError for missing values.'
191         if elem in self:
192             super().__delitem__(elem)
193 
194     def __repr__(self):
195         if not self:
196             return '%s()' % self.__class__.__name__
197         try:
198             items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
199             return '%s({%s})' % (self.__class__.__name__, items)
200         except TypeError:
201             # handle case where values are not orderable
202             return '{0}({1!r})'.format(self.__class__.__name__, dict(self))
203 
204     # Multiset-style mathematical operations discussed in:
205     #       Knuth TAOCP Volume II section 4.6.3 exercise 19
206     #       and at http://en.wikipedia.org/wiki/Multiset
207     #
208     # Outputs guaranteed to only include positive counts.
209     #
210     # To strip negative and zero counts, add-in an empty counter:
211     #       c += Counter()
212 
213     def __add__(self, other):
214         '''Add counts from two counters.
215 
216         >>> Counter('abbb') + Counter('bcc')
217         Counter({'b': 4, 'c': 2, 'a': 1})
218 
219         '''
220         if not isinstance(other, Counter):
221             return NotImplemented
222         result = Counter()
223         for elem, count in self.items():
224             newcount = count + other[elem]
225             if newcount > 0:
226                 result[elem] = newcount
227         for elem, count in other.items():
228             if elem not in self and count > 0:
229                 result[elem] = count
230         return result
231 
232     def __sub__(self, other):
233         ''' Subtract count, but keep only results with positive counts.
234 
235         >>> Counter('abbbc') - Counter('bccd')
236         Counter({'b': 2, 'a': 1})
237 
238         '''
239         if not isinstance(other, Counter):
240             return NotImplemented
241         result = Counter()
242         for elem, count in self.items():
243             newcount = count - other[elem]
244             if newcount > 0:
245                 result[elem] = newcount
246         for elem, count in other.items():
247             if elem not in self and count < 0:
248                 result[elem] = 0 - count
249         return result
250 
251     def __or__(self, other):
252         '''Union is the maximum of value in either of the input counters.
253 
254         >>> Counter('abbb') | Counter('bcc')
255         Counter({'b': 3, 'c': 2, 'a': 1})
256 
257         '''
258         if not isinstance(other, Counter):
259             return NotImplemented
260         result = Counter()
261         for elem, count in self.items():
262             other_count = other[elem]
263             newcount = other_count if count < other_count else count
264             if newcount > 0:
265                 result[elem] = newcount
266         for elem, count in other.items():
267             if elem not in self and count > 0:
268                 result[elem] = count
269         return result
270 
271     def __and__(self, other):
272         ''' Intersection is the minimum of corresponding counts.
273 
274         >>> Counter('abbb') & Counter('bcc')
275         Counter({'b': 1})
276 
277         '''
278         if not isinstance(other, Counter):
279             return NotImplemented
280         result = Counter()
281         for elem, count in self.items():
282             other_count = other[elem]
283             newcount = count if count < other_count else other_count
284             if newcount > 0:
285                 result[elem] = newcount
286         return result
287 
288     def __pos__(self):
289         'Adds an empty counter, effectively stripping negative and zero counts'
290         return self + Counter()
291 
292     def __neg__(self):
293         '''Subtracts from an empty counter.  Strips positive and zero counts,
294         and flips the sign on negative counts.
295 
296         '''
297         return Counter() - self
298 
299     def _keep_positive(self):
300         '''Internal method to strip elements with a negative or zero count'''
301         nonpositive = [elem for elem, count in self.items() if not count > 0]
302         for elem in nonpositive:
303             del self[elem]
304         return self
305 
306     def __iadd__(self, other):
307         '''Inplace add from another counter, keeping only positive counts.
308 
309         >>> c = Counter('abbb')
310         >>> c += Counter('bcc')
311         >>> c
312         Counter({'b': 4, 'c': 2, 'a': 1})
313 
314         '''
315         for elem, count in other.items():
316             self[elem] += count
317         return self._keep_positive()
318 
319     def __isub__(self, other):
320         '''Inplace subtract counter, but keep only results with positive counts.
321 
322         >>> c = Counter('abbbc')
323         >>> c -= Counter('bccd')
324         >>> c
325         Counter({'b': 2, 'a': 1})
326 
327         '''
328         for elem, count in other.items():
329             self[elem] -= count
330         return self._keep_positive()
331 
332     def __ior__(self, other):
333         '''Inplace union is the maximum of value from either counter.
334 
335         >>> c = Counter('abbb')
336         >>> c |= Counter('bcc')
337         >>> c
338         Counter({'b': 3, 'c': 2, 'a': 1})
339 
340         '''
341         for elem, other_count in other.items():
342             count = self[elem]
343             if other_count > count:
344                 self[elem] = other_count
345         return self._keep_positive()
346 
347     def __iand__(self, other):
348         '''Inplace intersection is the minimum of corresponding counts.
349 
350         >>> c = Counter('abbb')
351         >>> c &= Counter('bcc')
352         >>> c
353         Counter({'b': 1})
354 
355         '''
356         for elem, count in self.items():
357             other_count = other[elem]
358             if other_count < count:
359                 self[elem] = other_count
360         return self._keep_positive()
View Code

 二、有序字典(OrderedDict)

拥有字典的所有特性,另加自己的有序特性

from collections import OrderedDict

  1 class OrderedDict(dict):
  2     'Dictionary that remembers insertion order'
  3     # An inherited dict maps keys to values.
  4     # The inherited dict provides __getitem__, __len__, __contains__, and get.
  5     # The remaining methods are order-aware.
  6     # Big-O running times for all methods are the same as regular dictionaries.
  7 
  8     # The internal self.__map dict maps keys to links in a doubly linked list.
  9     # The circular doubly linked list starts and ends with a sentinel element.
 10     # The sentinel element never gets deleted (this simplifies the algorithm).
 11     # The sentinel is in self.__hardroot with a weakref proxy in self.__root.
 12     # The prev links are weakref proxies (to prevent circular references).
 13     # Individual links are kept alive by the hard reference in self.__map.
 14     # Those hard references disappear when a key is deleted from an OrderedDict.
 15 
 16     def __init__(self, *args, **kwds):
 17         '''Initialize an ordered dictionary.  The signature is the same as
 18         regular dictionaries, but keyword arguments are not recommended because
 19         their insertion order is arbitrary.
 20 
 21         '''
 22         if len(args) > 1:
 23             raise TypeError('expected at most 1 arguments, got %d' % len(args))
 24         try:
 25             self.__root
 26         except AttributeError:
 27             self.__hardroot = _Link()
 28             self.__root = root = _proxy(self.__hardroot)
 29             root.prev = root.next = root
 30             self.__map = {}
 31         self.__update(*args, **kwds)
 32 
 33     def __setitem__(self, key, value,
 34                     dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
 35         'od.__setitem__(i, y) <==> od[i]=y'
 36         # Setting a new item creates a new link at the end of the linked list,
 37         # and the inherited dictionary is updated with the new key/value pair.
 38         if key not in self:
 39             self.__map[key] = link = Link()
 40             root = self.__root
 41             last = root.prev
 42             link.prev, link.next, link.key = last, root, key
 43             last.next = link
 44             root.prev = proxy(link)
 45         dict_setitem(self, key, value)
 46 
 47     def __delitem__(self, key, dict_delitem=dict.__delitem__):
 48         'od.__delitem__(y) <==> del od[y]'
 49         # Deleting an existing item uses self.__map to find the link which gets
 50         # removed by updating the links in the predecessor and successor nodes.
 51         dict_delitem(self, key)
 52         link = self.__map.pop(key)
 53         link_prev = link.prev
 54         link_next = link.next
 55         link_prev.next = link_next
 56         link_next.prev = link_prev
 57 
 58     def __iter__(self):
 59         'od.__iter__() <==> iter(od)'
 60         # Traverse the linked list in order.
 61         root = self.__root
 62         curr = root.next
 63         while curr is not root:
 64             yield curr.key
 65             curr = curr.next
 66 
 67     def __reversed__(self):
 68         'od.__reversed__() <==> reversed(od)'
 69         # Traverse the linked list in reverse order.
 70         root = self.__root
 71         curr = root.prev
 72         while curr is not root:
 73             yield curr.key
 74             curr = curr.prev
 75 
 76     def clear(self):
 77         'od.clear() -> None.  Remove all items from od.'
 78         root = self.__root
 79         root.prev = root.next = root
 80         self.__map.clear()
 81         dict.clear(self)
 82 
 83     def popitem(self, last=True):
 84         '''od.popitem() -> (k, v), return and remove a (key, value) pair.
 85         Pairs are returned in LIFO order if last is true or FIFO order if false.
 86 
 87         '''
 88         if not self:
 89             raise KeyError('dictionary is empty')
 90         root = self.__root
 91         if last:
 92             link = root.prev
 93             link_prev = link.prev
 94             link_prev.next = root
 95             root.prev = link_prev
 96         else:
 97             link = root.next
 98             link_next = link.next
 99             root.next = link_next
100             link_next.prev = root
101         key = link.key
102         del self.__map[key]
103         value = dict.pop(self, key)
104         return key, value
105 
106     def move_to_end(self, key, last=True):
107         '''Move an existing element to the end (or beginning if last==False).
108                 将一个已存在的元素移到字典末尾,元素不存在则报错
109         Raises KeyError if the element does not exist.
110         When last=True, acts like a fast version of self[key]=self.pop(key).
111 
112         '''
113         link = self.__map[key]
114         link_prev = link.prev
115         link_next = link.next
116         link_prev.next = link_next
117         link_next.prev = link_prev
118         root = self.__root
119         if last:
120             last = root.prev
121             link.prev = last
122             link.next = root
123             last.next = root.prev = link
124         else:
125             first = root.next
126             link.prev = root
127             link.next = first
128             root.next = first.prev = link
129 
130     def __sizeof__(self):
131         sizeof = _sys.getsizeof
132         n = len(self) + 1                       # number of links including root
133         size = sizeof(self.__dict__)            # instance dictionary
134         size += sizeof(self.__map) * 2          # internal dict and inherited dict
135         size += sizeof(self.__hardroot) * n     # link objects
136         size += sizeof(self.__root) * n         # proxy objects
137         return size
138 
139     update = __update = MutableMapping.update
140     keys = MutableMapping.keys
141     values = MutableMapping.values
142     items = MutableMapping.items
143     __ne__ = MutableMapping.__ne__
144 
145     __marker = object()
146 
147     def pop(self, key, default=__marker):
148         '''od.pop(k[,d]) -> v, remove specified key and return the corresponding
149         value.  If key is not found, d is returned if given, otherwise KeyError
150         is raised.
151                 删除一个指定的键值,如果键不存在则报错
152         '''
153         if key in self:
154             result = self[key]
155             del self[key]
156             return result
157         if default is self.__marker:
158             raise KeyError(key)
159         return default
160 
161     def setdefault(self, key, default=None):
162         'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
163         如果键不存在,则set[k] = d
164         if key in self:
165             return self[key]
166         self[key] = default
167         return default
168 
169     @_recursive_repr()
170     def __repr__(self):
171         'od.__repr__() <==> repr(od)'
172         if not self:
173             return '%s()' % (self.__class__.__name__,)
174         return '%s(%r)' % (self.__class__.__name__, list(self.items()))
175 
176     def __reduce__(self):
177         'Return state information for pickling'
178         inst_dict = vars(self).copy()
179         for k in vars(OrderedDict()):
180             inst_dict.pop(k, None)
181         return self.__class__, (), inst_dict or None, None, iter(self.items())
182 
183     def copy(self):
184         'od.copy() -> a shallow copy of od'
185         return self.__class__(self)
186 
187     @classmethod
188     def fromkeys(cls, iterable, value=None):
189         '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
190         If not specified, the value defaults to None.
191 
192         '''
193         self = cls()
194         for key in iterable:
195             self[key] = value
196         return self
197 
198     def __eq__(self, other):
199         '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
200         while comparison to a regular mapping is order-insensitive.
201 
202         '''
203         if isinstance(other, OrderedDict):
204             return dict.__eq__(self, other) and all(map(_eq, self, other))
205         return dict.__eq__(self, other)
View Code

三、默认字典(defaultdict)

 拥有字典的所有特性,另加自己的有序特性

from collections import defaultdict

 1 class defaultdict(dict):
 2     """
 3     defaultdict(default_factory[, ...]) --> dict with default factory
 4     
 5     The default factory is called without arguments to produce
 6     a new value when a key is not present, in __getitem__ only.
 7     A defaultdict compares equal to a dict with the same items.
 8     All remaining arguments are treated the same as if they were
 9     passed to the dict constructor, including keyword arguments.
10     """
11     def copy(self): # real signature unknown; restored from __doc__
12         """ D.copy() -> a shallow copy of D. """
13         pass
14 
15     def __copy__(self, *args, **kwargs): # real signature unknown
16         """ D.copy() -> a shallow copy of D. """
17         pass
18 
19     def __getattribute__(self, *args, **kwargs): # real signature unknown
20         """ Return getattr(self, name). """
21         pass
22 
23     def __init__(self, default_factory=None, **kwargs): # known case of _collections.defaultdict.__init__
24         """
25         defaultdict(default_factory[, ...]) --> dict with default factory
26         
27         The default factory is called without arguments to produce
28         a new value when a key is not present, in __getitem__ only.
29         A defaultdict compares equal to a dict with the same items.
30         All remaining arguments are treated the same as if they were
31         passed to the dict constructor, including keyword arguments.
32         
33         # (copied from class doc)
34         """
35         pass
36 
37     def __missing__(self, key): # real signature unknown; restored from __doc__
38         """
39         __missing__(key) # Called by __getitem__ for missing key; pseudo-code:
40           if self.default_factory is None: raise KeyError((key,))
41           self[key] = value = self.default_factory()
42           return value
43         """
44         pass
45 
46     def __reduce__(self, *args, **kwargs): # real signature unknown
47         """ Return state information for pickling. """
48         pass
49 
50     def __repr__(self, *args, **kwargs): # real signature unknown
51         """ Return repr(self). """
52         pass
53 
54     default_factory = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
55     """Factory for default value called by __missing__()."""
View Code

示例:

c = defaultdict(list)
c['k1'].append('11')
print(c)
如果非默认字典,则直接append会报错

 四、可命名元组(namedtuple)

from collections import namedtuple

五、双向队列(deque)

一个线程安全的双向队列

from collections import deque

  1 class deque(object):
  2     """
  3     deque([iterable[, maxlen]]) --> deque object
  4     Build an ordered collection with optimized access from its endpoints.
  5     """
  6     def append(self, *args, **kwargs): # real signature unknown
  7         """ Add an element to the right side of the deque. """
  8         pass
  9 
 10     def appendleft(self, *args, **kwargs): # real signature unknown
 11         """ Add an element to the left side of the deque. """
 12         pass
 13 
 14     def clear(self, *args, **kwargs): # real signature unknown
 15         """ Remove all elements from the deque. """
 16         pass
 17 
 18     def count(self, value): # real signature unknown; restored from __doc__
 19         """ D.count(value) -> integer -- return number of occurrences of value """
 20         return 0
 21 
 22     def extend(self, *args, **kwargs): # real signature unknown
 23         """ Extend the right side of the deque with elements from the iterable """
 24         使用迭代中的元素扩展队列的右侧
 25         pass
 26 
 27     def extendleft(self, *args, **kwargs): # real signature unknown
 28         """ Extend the left side of the deque with elements from the iterable """
 29         pass
 30 
 31     def pop(self, *args, **kwargs): # real signature unknown
 32         """ Remove and return the rightmost element. """
 33         pass
 34 
 35     def popleft(self, *args, **kwargs): # real signature unknown
 36         """ Remove and return the leftmost element. """
 37         pass
 38 
 39     def remove(self, value): # real signature unknown; restored from __doc__
 40         """ D.remove(value) -- remove first occurrence of value. """
 41         pass
 42 
 43     def reverse(self): # real signature unknown; restored from __doc__
 44         """ D.reverse() -- reverse *IN PLACE* """
 45         反转队列
 46         pass
 47 
 48     def rotate(self, *args, **kwargs): # real signature unknown
 49         """ Rotate the deque n steps to the right (default n=1).  If n is negative, rotates left. """
 50         旋转队列
 51         pass
 52 
 53     def __copy__(self, *args, **kwargs): # real signature unknown
 54         """ Return a shallow copy of a deque. """
 55         pass
 56 
 57     def __delitem__(self, *args, **kwargs): # real signature unknown
 58         """ Delete self[key]. """
 59         pass
 60 
 61     def __eq__(self, *args, **kwargs): # real signature unknown
 62         """ Return self==value. """
 63         pass
 64 
 65     def __getattribute__(self, *args, **kwargs): # real signature unknown
 66         """ Return getattr(self, name). """
 67         pass
 68 
 69     def __getitem__(self, *args, **kwargs): # real signature unknown
 70         """ Return self[key]. """
 71         pass
 72 
 73     def __ge__(self, *args, **kwargs): # real signature unknown
 74         """
 75         __ge__=($self, value, /)
 76         --
 77         
 78         Return self>=value.
 79         """
 80         pass
 81 
 82     def __gt__(self, *args, **kwargs): # real signature unknown
 83         """ Return self>value. """
 84         pass
 85 
 86     def __iadd__(self, *args, **kwargs): # real signature unknown
 87         """ Implement self+=value. """
 88         pass
 89 
 90     def __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__
 91         """
 92         deque([iterable[, maxlen]]) --> deque object
 93         
 94         Build an ordered collection with optimized access from its endpoints.
 95         # (copied from class doc)
 96         """
 97         pass
 98 
 99     def __iter__(self, *args, **kwargs): # real signature unknown
100         """ Implement iter(self). """
101         pass
102 
103     def __len__(self, *args, **kwargs): # real signature unknown
104         """ Return len(self). """
105         pass
106 
107     def __le__(self, *args, **kwargs): # real signature unknown
108         """ Return self<=value. """
109         pass
110 
111     def __lt__(self, *args, **kwargs): # real signature unknown
112         """ Return self<value. """
113         pass
114 
115     @staticmethod # known case of __new__
116     def __new__(*args, **kwargs): # real signature unknown
117         """ Create and return a new object.  See help(type) for accurate signature. """
118         pass
119 
120     def __ne__(self, *args, **kwargs): # real signature unknown
121         """ Return self!=value. """
122         pass
123 
124     def __reduce__(self, *args, **kwargs): # real signature unknown
125         """ Return state information for pickling. """
126         pass
127 
128     def __repr__(self, *args, **kwargs): # real signature unknown
129         """ Return repr(self). """
130         pass
131 
132     def __reversed__(self): # real signature unknown; restored from __doc__
133         """ D.__reversed__() -- return a reverse iterator over the deque """
134         pass
135 
136     def __setitem__(self, *args, **kwargs): # real signature unknown
137         """ Set self[key] to value. """
138         pass
139 
140     def __sizeof__(self): # real signature unknown; restored from __doc__
141         """ D.__sizeof__() -- size of D in memory, in bytes """
142         pass
143 
144     maxlen = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
145     """maximum size of a deque or None if unbounded"""
146 
147 
148     __hash__ = None
View Code

六、单向队列(queue.queue)

先进先出

待叙。。。。。


原文地址:https://www.cnblogs.com/kongzhagen/p/5451615.html