collections
collections是Python数据类型的补充,可以实现Counter计数、可命名元组(namedtuple)、默认字典、有序字典、双向队列等功能
参考:http://python.usyiyi.cn/python_278/library/collections.html
Help on module collections: NAME collections FILE c:\python27\lib\collections.py CLASSES __builtin__.dict(__builtin__.object) Counter OrderedDict defaultdict __builtin__.object _abcoll.Callable _abcoll.Container _abcoll.Hashable _abcoll.Iterable _abcoll.Iterator _abcoll.Sized _abcoll.Mapping(_abcoll.Sized, _abcoll.Iterable, _abcoll.Container) _abcoll.MutableMapping _abcoll.MappingView _abcoll.ItemsView(_abcoll.MappingView, _abcoll.Set) _abcoll.KeysView(_abcoll.MappingView, _abcoll.Set) _abcoll.ValuesView _abcoll.Sequence(_abcoll.Sized, _abcoll.Iterable, _abcoll.Container) _abcoll.MutableSequence _abcoll.Set(_abcoll.Sized, _abcoll.Iterable, _abcoll.Container) _abcoll.MutableSet deque class Callable(__builtin__.object) | Methods defined here: | | __call__(self, *args, **kwds) | | ---------------------------------------------------------------------- | Class methods defined here: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__call__']) | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class Container(__builtin__.object) | Methods defined here: | | __contains__(self, x) | | ---------------------------------------------------------------------- | Class methods defined here: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__contains__']) | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class Counter(__builtin__.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)] | | Method resolution order: | Counter | __builtin__.dict | __builtin__.object | | Methods defined here: | | __add__(self, other) | Add counts from two counters. | | >>> Counter('abbb') + Counter('bcc') | Counter({'b': 4, 'c': 2, 'a': 1}) | | __and__(self, other) | Intersection is the minimum of corresponding counts. | | >>> Counter('abbb') & Counter('bcc') | Counter({'b': 1}) | | __delitem__(self, elem) | Like dict.__delitem__() but does not raise KeyError for missing values. | | __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 | | __missing__(self, key) | The count of elements not in the Counter is zero. | | __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}) | | __reduce__(self) | | __repr__(self) | | __sub__(self, other) | Subtract count, but keep only results with positive counts. | | >>> Counter('abbbc') - Counter('bccd') | Counter({'b': 2, 'a': 1}) | | copy(self) | Return a shallow copy. | | 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. | | 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)] | | 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 | | update(*args, **kwds) | 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 | | ---------------------------------------------------------------------- | Class methods defined here: | | fromkeys(cls, iterable, v=None) from __builtin__.type | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from __builtin__.dict: | | __cmp__(...) | x.__cmp__(y) <==> cmp(x,y) | | __contains__(...) | D.__contains__(k) -> True if D has a key k, else False | | __eq__(...) | x.__eq__(y) <==> x==y | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(...) | x.__gt__(y) <==> x>y | | __iter__(...) | x.__iter__() <==> iter(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __setitem__(...) | x.__setitem__(i, y) <==> x[i]=y | | __sizeof__(...) | D.__sizeof__() -> size of D in memory, in bytes | | clear(...) | D.clear() -> None. Remove all items from D. | | get(...) | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. | | has_key(...) | D.has_key(k) -> True if D has a key k, else False | | items(...) | D.items() -> list of D's (key, value) pairs, as 2-tuples | | iteritems(...) | D.iteritems() -> an iterator over the (key, value) items of D | | iterkeys(...) | D.iterkeys() -> an iterator over the keys of D | | itervalues(...) | D.itervalues() -> an iterator over the values of D | | keys(...) | D.keys() -> list of D's keys | | pop(...) | D.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 | | popitem(...) | D.popitem() -> (k, v), remove and return some (key, value) pair as a | 2-tuple; but raise KeyError if D is empty. | | setdefault(...) | D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D | | values(...) | D.values() -> list of D's values | | viewitems(...) | D.viewitems() -> a set-like object providing a view on D's items | | viewkeys(...) | D.viewkeys() -> a set-like object providing a view on D's keys | | viewvalues(...) | D.viewvalues() -> an object providing a view on D's values | | ---------------------------------------------------------------------- | Data and other attributes inherited from __builtin__.dict: | | __hash__ = None | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T class Hashable(__builtin__.object) | Methods defined here: | | __hash__(self) | | ---------------------------------------------------------------------- | Class methods defined here: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__hash__']) | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class ItemsView(MappingView, Set) | Method resolution order: | ItemsView | MappingView | Set | Sized | Iterable | Container | __builtin__.object | | Methods defined here: | | __contains__(self, item) | | __iter__(self) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset([]) | | ---------------------------------------------------------------------- | Methods inherited from MappingView: | | __init__(self, mapping) | | __len__(self) | | __repr__(self) | | ---------------------------------------------------------------------- | Methods inherited from Set: | | __and__(self, other) | | __eq__(self, other) | | __ge__(self, other) | | __gt__(self, other) | | __le__(self, other) | | __lt__(self, other) | | __ne__(self, other) | | __or__(self, other) | | __rand__ = __and__(self, other) | | __ror__ = __or__(self, other) | | __rsub__(self, other) | | __rxor__ = __xor__(self, other) | | __sub__(self, other) | | __xor__(self, other) | | isdisjoint(self, other) | Return True if two sets have a null intersection. | | ---------------------------------------------------------------------- | Data and other attributes inherited from Set: | | __hash__ = None | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class Iterable(__builtin__.object) | Methods defined here: | | __iter__(self) | | ---------------------------------------------------------------------- | Class methods defined here: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__iter__']) | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class Iterator(Iterable) | Method resolution order: | Iterator | Iterable | __builtin__.object | | Methods defined here: | | __iter__(self) | | next(self) | Return the next item from the iterator. When exhausted, raise StopIteration | | ---------------------------------------------------------------------- | Class methods defined here: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['next']) | | ---------------------------------------------------------------------- | Data descriptors inherited from Iterable: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Iterable: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class KeysView(MappingView, Set) | Method resolution order: | KeysView | MappingView | Set | Sized | Iterable | Container | __builtin__.object | | Methods defined here: | | __contains__(self, key) | | __iter__(self) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset([]) | | ---------------------------------------------------------------------- | Methods inherited from MappingView: | | __init__(self, mapping) | | __len__(self) | | __repr__(self) | | ---------------------------------------------------------------------- | Methods inherited from Set: | | __and__(self, other) | | __eq__(self, other) | | __ge__(self, other) | | __gt__(self, other) | | __le__(self, other) | | __lt__(self, other) | | __ne__(self, other) | | __or__(self, other) | | __rand__ = __and__(self, other) | | __ror__ = __or__(self, other) | | __rsub__(self, other) | | __rxor__ = __xor__(self, other) | | __sub__(self, other) | | __xor__(self, other) | | isdisjoint(self, other) | Return True if two sets have a null intersection. | | ---------------------------------------------------------------------- | Data and other attributes inherited from Set: | | __hash__ = None | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class Mapping(Sized, Iterable, Container) | A Mapping is a generic container for associating key/value | pairs. | | This class provides concrete generic implementations of all | methods except for __getitem__, __iter__, and __len__. | | Method resolution order: | Mapping | Sized | Iterable | Container | __builtin__.object | | Methods defined here: | | __contains__(self, key) | | __eq__(self, other) | | __getitem__(self, key) | | __ne__(self, other) | | get(self, key, default=None) | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. | | items(self) | D.items() -> list of D's (key, value) pairs, as 2-tuples | | iteritems(self) | D.iteritems() -> an iterator over the (key, value) items of D | | iterkeys(self) | D.iterkeys() -> an iterator over the keys of D | | itervalues(self) | D.itervalues() -> an iterator over the values of D | | keys(self) | D.keys() -> list of D's keys | | values(self) | D.values() -> list of D's values | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__getitem__', '__iter__', '__len__']... | | __hash__ = None | | ---------------------------------------------------------------------- | Methods inherited from Sized: | | __len__(self) | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). | | ---------------------------------------------------------------------- | Methods inherited from Iterable: | | __iter__(self) class MappingView(Sized) | Method resolution order: | MappingView | Sized | __builtin__.object | | Methods defined here: | | __init__(self, mapping) | | __len__(self) | | __repr__(self) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset([]) | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class MutableMapping(Mapping) | A MutableMapping is a generic container for associating | key/value pairs. | | This class provides concrete generic implementations of all | methods except for __getitem__, __setitem__, __delitem__, | __iter__, and __len__. | | Method resolution order: | MutableMapping | Mapping | Sized | Iterable | Container | __builtin__.object | | Methods defined here: | | __delitem__(self, key) | | __setitem__(self, key, value) | | clear(self) | D.clear() -> None. Remove all items from D. | | pop(self, key, default=<object object>) | D.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. | | popitem(self) | D.popitem() -> (k, v), remove and return some (key, value) pair | as a 2-tuple; but raise KeyError if D is empty. | | setdefault(self, key, default=None) | D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D | | update(*args, **kwds) | D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. | If E present and has a .keys() method, does: for k in E: D[k] = E[k] | If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v | In either case, this is followed by: for k, v in F.items(): D[k] = v | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__delitem__', '__getitem__', '__iter... | | ---------------------------------------------------------------------- | Methods inherited from Mapping: | | __contains__(self, key) | | __eq__(self, other) | | __getitem__(self, key) | | __ne__(self, other) | | get(self, key, default=None) | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. | | items(self) | D.items() -> list of D's (key, value) pairs, as 2-tuples | | iteritems(self) | D.iteritems() -> an iterator over the (key, value) items of D | | iterkeys(self) | D.iterkeys() -> an iterator over the keys of D | | itervalues(self) | D.itervalues() -> an iterator over the values of D | | keys(self) | D.keys() -> list of D's keys | | values(self) | D.values() -> list of D's values | | ---------------------------------------------------------------------- | Data and other attributes inherited from Mapping: | | __hash__ = None | | ---------------------------------------------------------------------- | Methods inherited from Sized: | | __len__(self) | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). | | ---------------------------------------------------------------------- | Methods inherited from Iterable: | | __iter__(self) class MutableSequence(Sequence) | All the operations on a read-only sequence. | | Concrete subclasses must provide __new__ or __init__, | __getitem__, __setitem__, __delitem__, __len__, and insert(). | | Method resolution order: | MutableSequence | Sequence | Sized | Iterable | Container | __builtin__.object | | Methods defined here: | | __delitem__(self, index) | | __iadd__(self, values) | | __setitem__(self, index, value) | | append(self, value) | S.append(object) -- append object to the end of the sequence | | extend(self, values) | S.extend(iterable) -- extend sequence by appending elements from the iterable | | insert(self, index, value) | S.insert(index, object) -- insert object before index | | pop(self, index=-1) | S.pop([index]) -> item -- remove and return item at index (default last). | Raise IndexError if list is empty or index is out of range. | | remove(self, value) | S.remove(value) -- remove first occurrence of value. | Raise ValueError if the value is not present. | | reverse(self) | S.reverse() -- reverse *IN PLACE* | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__delitem__', '__getitem__', '__len_... | | ---------------------------------------------------------------------- | Methods inherited from Sequence: | | __contains__(self, value) | | __getitem__(self, index) | | __iter__(self) | | __reversed__(self) | | count(self, value) | S.count(value) -> integer -- return number of occurrences of value | | index(self, value) | S.index(value) -> integer -- return first index of value. | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Methods inherited from Sized: | | __len__(self) | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class MutableSet(Set) | A mutable set is a finite, iterable container. | | This class provides concrete generic implementations of all | methods except for __contains__, __iter__, __len__, | add(), and discard(). | | To override the comparisons (presumably for speed, as the | semantics are fixed), all you have to do is redefine __le__ and | then the other operations will automatically follow suit. | | Method resolution order: | MutableSet | Set | Sized | Iterable | Container | __builtin__.object | | Methods defined here: | | __iand__(self, it) | | __ior__(self, it) | | __isub__(self, it) | | __ixor__(self, it) | | add(self, value) | Add an element. | | clear(self) | This is slow (creates N new iterators!) but effective. | | discard(self, value) | Remove an element. Do not raise an exception if absent. | | pop(self) | Return the popped value. Raise KeyError if empty. | | remove(self, value) | Remove an element. If not a member, raise a KeyError. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__contains__', '__iter__', '__len__'... | | ---------------------------------------------------------------------- | Methods inherited from Set: | | __and__(self, other) | | __eq__(self, other) | | __ge__(self, other) | | __gt__(self, other) | | __le__(self, other) | | __lt__(self, other) | | __ne__(self, other) | | __or__(self, other) | | __rand__ = __and__(self, other) | | __ror__ = __or__(self, other) | | __rsub__(self, other) | | __rxor__ = __xor__(self, other) | | __sub__(self, other) | | __xor__(self, other) | | isdisjoint(self, other) | Return True if two sets have a null intersection. | | ---------------------------------------------------------------------- | Data and other attributes inherited from Set: | | __hash__ = None | | ---------------------------------------------------------------------- | Methods inherited from Sized: | | __len__(self) | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). | | ---------------------------------------------------------------------- | Methods inherited from Iterable: | | __iter__(self) | | ---------------------------------------------------------------------- | Methods inherited from Container: | | __contains__(self, x) class OrderedDict(__builtin__.dict) | Dictionary that remembers insertion order | | Method resolution order: | OrderedDict | __builtin__.dict | __builtin__.object | | Methods defined here: | | __delitem__(self, key, dict_delitem=<slot wrapper '__delitem__' of 'dict' objects>) | od.__delitem__(y) <==> del od[y] | | __eq__(self, other) | od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive | while comparison to a regular mapping is order-insensitive. | | __init__(*args, **kwds) | Initialize an ordered dictionary. The signature is the same as | regular dictionaries, but keyword arguments are not recommended because | their insertion order is arbitrary. | | __iter__(self) | od.__iter__() <==> iter(od) | | __ne__(self, other) | od.__ne__(y) <==> od!=y | | __reduce__(self) | Return state information for pickling | | __repr__(self, _repr_running={}) | od.__repr__() <==> repr(od) | | __reversed__(self) | od.__reversed__() <==> reversed(od) | | __setitem__(self, key, value, dict_setitem=<slot wrapper '__setitem__' of 'dict' objects>) | od.__setitem__(i, y) <==> od[i]=y | | clear(self) | od.clear() -> None. Remove all items from od. | | copy(self) | od.copy() -> a shallow copy of od | | items(self) | od.items() -> list of (key, value) pairs in od | | iteritems(self) | od.iteritems -> an iterator over the (key, value) pairs in od | | iterkeys(self) | od.iterkeys() -> an iterator over the keys in od | | itervalues(self) | od.itervalues -> an iterator over the values in od | | keys(self) | od.keys() -> list of keys in od | | pop(self, key, default=<object object>) | 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. | | popitem(self, last=True) | 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. | | setdefault(self, key, default=None) | od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od | | update(*args, **kwds) | D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. | If E present and has a .keys() method, does: for k in E: D[k] = E[k] | If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v | In either case, this is followed by: for k, v in F.items(): D[k] = v | | values(self) | od.values() -> list of values in od | | viewitems(self) | od.viewitems() -> a set-like object providing a view on od's items | | viewkeys(self) | od.viewkeys() -> a set-like object providing a view on od's keys | | viewvalues(self) | od.viewvalues() -> an object providing a view on od's values | | ---------------------------------------------------------------------- | Class methods defined here: | | fromkeys(cls, iterable, value=None) from __builtin__.type | OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S. | If not specified, the value defaults to None. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from __builtin__.dict: | | __cmp__(...) | x.__cmp__(y) <==> cmp(x,y) | | __contains__(...) | D.__contains__(k) -> True if D has a key k, else False | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(...) | x.__gt__(y) <==> x>y | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __sizeof__(...) | D.__sizeof__() -> size of D in memory, in bytes | | get(...) | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. | | has_key(...) | D.has_key(k) -> True if D has a key k, else False | | ---------------------------------------------------------------------- | Data and other attributes inherited from __builtin__.dict: | | __hash__ = None | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T class Sequence(Sized, Iterable, Container) | All the operations on a read-only sequence. | | Concrete subclasses must override __new__ or __init__, | __getitem__, and __len__. | | Method resolution order: | Sequence | Sized | Iterable | Container | __builtin__.object | | Methods defined here: | | __contains__(self, value) | | __getitem__(self, index) | | __iter__(self) | | __reversed__(self) | | count(self, value) | S.count(value) -> integer -- return number of occurrences of value | | index(self, value) | S.index(value) -> integer -- return first index of value. | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__getitem__', '__len__']) | | ---------------------------------------------------------------------- | Methods inherited from Sized: | | __len__(self) | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class Set(Sized, Iterable, Container) | A set is a finite, iterable container. | | This class provides concrete generic implementations of all | methods except for __contains__, __iter__ and __len__. | | To override the comparisons (presumably for speed, as the | semantics are fixed), redefine __le__ and __ge__, | then the other operations will automatically follow suit. | | Method resolution order: | Set | Sized | Iterable | Container | __builtin__.object | | Methods defined here: | | __and__(self, other) | | __eq__(self, other) | | __ge__(self, other) | | __gt__(self, other) | | __le__(self, other) | | __lt__(self, other) | | __ne__(self, other) | | __or__(self, other) | | __rand__ = __and__(self, other) | | __ror__ = __or__(self, other) | | __rsub__(self, other) | | __rxor__ = __xor__(self, other) | | __sub__(self, other) | | __xor__(self, other) | | isdisjoint(self, other) | Return True if two sets have a null intersection. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__contains__', '__iter__', '__len__'... | | __hash__ = None | | ---------------------------------------------------------------------- | Methods inherited from Sized: | | __len__(self) | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). | | ---------------------------------------------------------------------- | Methods inherited from Iterable: | | __iter__(self) | | ---------------------------------------------------------------------- | Methods inherited from Container: | | __contains__(self, x) class Sized(__builtin__.object) | Methods defined here: | | __len__(self) | | ---------------------------------------------------------------------- | Class methods defined here: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__len__']) | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class ValuesView(MappingView) | Method resolution order: | ValuesView | MappingView | Sized | __builtin__.object | | Methods defined here: | | __contains__(self, value) | | __iter__(self) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset([]) | | ---------------------------------------------------------------------- | Methods inherited from MappingView: | | __init__(self, mapping) | | __len__(self) | | __repr__(self) | | ---------------------------------------------------------------------- | Class methods inherited from Sized: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors inherited from Sized: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes inherited from Sized: | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()). class defaultdict(__builtin__.dict) | defaultdict(default_factory[, ...]) --> dict with default factory | | The default factory is called without arguments to produce | a new value when a key is not present, in __getitem__ only. | A defaultdict compares equal to a dict with the same items. | All remaining arguments are treated the same as if they were | passed to the dict constructor, including keyword arguments. | | Method resolution order: | defaultdict | __builtin__.dict | __builtin__.object | | Methods defined here: | | __copy__(...) | D.copy() -> a shallow copy of D. | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | __missing__(...) | __missing__(key) # Called by __getitem__ for missing key; pseudo-code: | if self.default_factory is None: raise KeyError((key,)) | self[key] = value = self.default_factory() | return value | | __reduce__(...) | Return state information for pickling. | | __repr__(...) | x.__repr__() <==> repr(x) | | copy(...) | D.copy() -> a shallow copy of D. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | default_factory | Factory for default value called by __missing__(). | | ---------------------------------------------------------------------- | Methods inherited from __builtin__.dict: | | __cmp__(...) | x.__cmp__(y) <==> cmp(x,y) | | __contains__(...) | D.__contains__(k) -> True if D has a key k, else False | | __delitem__(...) | x.__delitem__(y) <==> del x[y] | | __eq__(...) | x.__eq__(y) <==> x==y | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(...) | x.__gt__(y) <==> x>y | | __iter__(...) | x.__iter__() <==> iter(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __setitem__(...) | x.__setitem__(i, y) <==> x[i]=y | | __sizeof__(...) | D.__sizeof__() -> size of D in memory, in bytes | | clear(...) | D.clear() -> None. Remove all items from D. | | fromkeys(...) | dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. | v defaults to None. | | get(...) | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. | | has_key(...) | D.has_key(k) -> True if D has a key k, else False | | items(...) | D.items() -> list of D's (key, value) pairs, as 2-tuples | | iteritems(...) | D.iteritems() -> an iterator over the (key, value) items of D | | iterkeys(...) | D.iterkeys() -> an iterator over the keys of D | | itervalues(...) | D.itervalues() -> an iterator over the values of D | | keys(...) | D.keys() -> list of D's keys | | pop(...) | D.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 | | popitem(...) | D.popitem() -> (k, v), remove and return some (key, value) pair as a | 2-tuple; but raise KeyError if D is empty. | | setdefault(...) | D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D | | update(...) | D.update([E, ]**F) -> None. Update D from dict/iterable E and F. | If E present and has a .keys() method, does: for k in E: D[k] = E[k] | If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v | In either case, this is followed by: for k in F: D[k] = F[k] | | values(...) | D.values() -> list of D's values | | viewitems(...) | D.viewitems() -> a set-like object providing a view on D's items | | viewkeys(...) | D.viewkeys() -> a set-like object providing a view on D's keys | | viewvalues(...) | D.viewvalues() -> an object providing a view on D's values | | ---------------------------------------------------------------------- | Data and other attributes inherited from __builtin__.dict: | | __hash__ = None | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T class deque(__builtin__.object) | deque([iterable[, maxlen]]) --> deque object | | Build an ordered collection with optimized access from its endpoints. | | Methods defined here: | | __copy__(...) | Return a shallow copy of a deque. | | __delitem__(...) | x.__delitem__(y) <==> del x[y] | | __eq__(...) | x.__eq__(y) <==> x==y | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(...) | x.__gt__(y) <==> x>y | | __iadd__(...) | x.__iadd__(y) <==> x+=y | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | __iter__(...) | x.__iter__() <==> iter(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __reduce__(...) | Return state information for pickling. | | __repr__(...) | x.__repr__() <==> repr(x) | | __reversed__(...) | D.__reversed__() -- return a reverse iterator over the deque | | __setitem__(...) | x.__setitem__(i, y) <==> x[i]=y | | __sizeof__(...) | D.__sizeof__() -- size of D in memory, in bytes | | append(...) | Add an element to the right side of the deque. | | appendleft(...) | Add an element to the left side of the deque. | | clear(...) | Remove all elements from the deque. | | count(...) | D.count(value) -> integer -- return number of occurrences of value | | extend(...) | Extend the right side of the deque with elements from the iterable | | extendleft(...) | Extend the left side of the deque with elements from the iterable | | pop(...) | Remove and return the rightmost element. | | popleft(...) | Remove and return the leftmost element. | | remove(...) | D.remove(value) -- remove first occurrence of value. | | reverse(...) | D.reverse() -- reverse *IN PLACE* | | rotate(...) | Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | maxlen | maximum size of a deque or None if unbounded | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T FUNCTIONS namedtuple(typename, field_names, verbose=False, rename=False) Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessable by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22) DATA __all__ = ['Counter', 'deque', 'defaultdict', 'namedtuple', 'OrderedDi...
collections内置方法
1、Counter
Counter接收一个序列型的数据,统计元素出现的个数,以字典的形式返回数据,具备字典和自己的功能,它是字典的子类.
要统计一个列表中元素出现的次数,可以这样做:
data = dict() some = ['a','b','a','b','c','b','a',1,2,1,1,3,3,4,4,1,2,5,5] for item in some: if item in data.keys(): data[item] += 1 else: data[item] = 1 print data {'a': 3, 1: 4, 'c': 1, 'b': 3, 4: 2, 5: 2, 2: 2, 3: 2}或者可以:
some = ['a','b','a','b','c','b','a',1,2,1,1,3,3,4,4,1,2,5,5] uniq = set(some) reslut = [] for item in uniq: if item in some: reslut.append((item,some.count(item)) data = dict(reslut) print reslut print data [('a', 3), (1, 4), ('c', 1), ('b', 3), (4, 2), (5, 2), (2, 2), (3, 2)] {'a': 3, 1: 4, 'c': 1, 'b': 3, 4: 2, 5: 2, 2: 2, 3: 2}用Counter来解决:
>>> import collections >>> some = ['a','b','a','b','c','b','a',1,2,1,1,3,3,4,4,1,2,5,5] >>> data = collections.Counter(some) >>> data Counter({1: 4, 'a': 3, 'b': 3, 4: 2, 5: 2, 2: 2, 3: 2, 'c': 1})其它的功能:
列出元素出现的top3
>>> data Counter({1: 4, 'a': 3, 'b': 3, 4: 2, 5: 2, 2: 2, 3: 2, 'c': 1}) >>> >>> data.most_common(3) [(1, 4), ('a', 3), ('b', 3)]sorted(data) #列出所有的元素,也就是key
>>> sorted(data) [1, 2, 3, 4, 5, 'a', 'b', 'c']//counter在有些情况下比较方便,其他的就和字典的功能一样,因为是继承的就是dict的功能
2、有序字典(OrderedDict)
我们知道字典的key是无序的,可以利用OrderedDict实现有序,它的原理是利用list来保证key的有序,因为是list是有序的。它具有字典与自己的功能
OrderedDict>>> dic = collections.OrderedDict() >>> dic['key1'] = 'v1' >>> dic['key2'] = 'v2' >>> dic['key3'] = 'v3' >>> dic OrderedDict([('key1', 'v1'), ('key2', 'v2'), ('key3', 'v3')]) #有序
3、默认字典(defaultdict)
默认字典可以设置value的默认类型
>>> dict1 = collections.defalutdict(list) >>> dic = collections.defaultdict(list) >>> dic['key1'].append(1) >>> dic['key2'].append(2) >>> dic defaultdict(<type 'list'>, {'key2': [2], 'key1': [1]})场景1:将[11,22,44,69,88,22,43,55,97]大于43的元素放到字典中
import collections dic = collections.defaultdict(list) li = [11,22,44,69,88,22,43,55,97] for number in li: if number > 60: dic['key1'].append(number) else: dic['key2'].append(number) print dic defaultdict(<type 'list'>, {'key2': [11, 22, 44, 22, 43, 55], 'key1': [69, 88, 97]})//其实就是预设value的类型
4、deque(双向队列)
双向队列,两边都以插入数据,抛出数据。线程安全,多个线程来拿数据,谁先拿就加锁
>>> q = collections.deque() >>> q.append(1) >>> q.append(11) >>> q.append(12) >>> q.append(13) >>> print q deque([1, 11, 12, 13]) >>> q.pop() # 弹出并返回最右边的元素, 13 >>> q deque([1, 11, 12]) >>> q.popleft() # 从左边弹出并返回一个元素 1 >>> q deque([11, 12])
PS:其他功能和列表类似
5、单向队列 (Queue)
生成者、消费者模型,相当于程序领任务,没有就等着,有就拿,也是线程安全. Queue是在Queue模块中
队列:FIFO,先进先出,栈:后进先出
>>> import Queue >>> q = Queue.Queue(6) # 6个数据 >>> q.put(1) # 推送一个数据 >>> q.put(2) >>> q.put(3) >>> q.get(1) # 取数据 1 >>> q.get(2) 2 >>> q.get(3) 3 >>> q.get(4) # 如果取完了就一直等待
6、Iterable
Iterable是collections模块中的一个类,可以用来判断一个对象是不是迭代的对象
class Iterable(__builtin__.object) | Methods defined here: | | __iter__(self) | | ---------------------------------------------------------------------- | Class methods defined here: | | __subclasshook__(cls, C) from abc.ABCMeta | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __abstractmethods__ = frozenset(['__iter__']) | | __metaclass__ = <class 'abc.ABCMeta'> | Metaclass for defining Abstract Base Classes (ABCs). | | Use this metaclass to create an ABC. An ABC can be subclassed | directly, and then acts as a mix-in class. You can also register | unrelated concrete classes (even built-in classes) and unrelated | ABCs as 'virtual subclasses' -- these and their descendants will | be considered subclasses of the registering ABC by the built-in | issubclass() function, but the registering ABC won't show up in | their MRO (Method Resolution Order) nor will method | implementations defined by the registering ABC be callable (not | even via super()).Iterable
>>> from collections import Iterable >>> obj1 = 123 >>> obj2 = 'string' >>> obj3 = [1,2,3] >>> obj4 = {} >>> isinstance(obj1,Iterable) # 数字是不可迭代的对象 False >>> isinstance(obj2,Iterable) # 字符串是可迭代的对象 True >>> isinstance(obj3,Iterable) # 列表是可迭代的对象 True >>> isinstance(obj4,Iterable) # 字典是可迭代的对象 True
总结:
collections封装了一些方法,有序字典,默认字典、Couter计数等, 有些情况下很有用