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

 class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object Build an unordered collection of unique elements.
打造唯一元素的无序集合
"""
def add(self, *args, **kwargs): # real signature unknown
"""
Add an element to a set.
增加一个元素到集合
eg:
s1 = set([,,])
s1.add() This has no effect if the element is already present. """
pass def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. """
移除集合中所有元素
pass def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. """
浅拷贝
pass def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set.
返回两个或多个集合的不同为一个新的集合
eg:
old_dict = set([,,,,,,])
# cmdb 新汇报的数据
new_dict = set([,,,,])
now_dict = set([,,,,])
print(old_dict.difference(new_dict,now_dict))
(i.e. all elements that are in this set but not the others.)
"""
pass def difference_update(self, *args, **kwargs): # real signature unknown
""" Remove all elements of another set from this set.
从当前集合中移除另一集合的所有元素,当前集合被改变
eg:
old_dict = set([,,,,,,])
# cmdb 新汇报的数据
new_dict = set([,,,,])
old_dict.difference_update(new_dict)
print(old_dict)
"""
pass def discard(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set if it is a member.
移除一个集合的中一个元素,如果没有则什么都不做
If the element is not a member, do nothing.
"""
pass def intersection(self, *args, **kwargs): # real signature unknown
"""
Return the intersection of two sets as a new set.
返回两个集合的交集为一个新的集合
(i.e. all elements that are in both sets.)
"""
pass def intersection_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the intersection of itself and another.
更新一个集合,使用它和另一集合的交集
eg:
old_dict = set([,,,,])
new_dict = set([,,,,])
print(old_dict)
"""
pass def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection.
如果两个集合没有交集则返回真
"""
pass def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set.
如果此集合包含在另一集合中,则返回真
eg:
old_dict = set([,,,,,,,])
# cmdb 新汇报的数据
new_dict = set([,,,])
print(new_dict.issubset(old_dict))
"""
pass def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set.
此集合包含另一集合则返回真
old_dict = set([,,,,,,,])
# cmdb 新汇报的数据
new_dict = set([,,,])
print(old_dict.issuperset(new_dict))
"""
pass def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty.
随机移除集合中的一个元素
eg:
old_dict = set([,,,,,,,])
print(old_dict.pop())
"""
pass def remove(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set; it must be a member.
移出集合中的一个元素,如果元素不存在则报错
If the element is not a member, raise a KeyError.
"""
pass def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set.
(i.e. all elements that are in exactly one of the sets.)
"""
pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the symmetric difference of itself and another. """
pass def union(self, *args, **kwargs): # real signature unknown
"""
Return the union of sets as a new set.
返回两个集合的合集为一个新的集合
(i.e. all elements that are in either set.)
"""
pass def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others.
更新此集合,使用此集合与另一集合的合集
"""
pass def __and__(self, *args, **kwargs): # real signature unknown
""" Return self&value. """
pass def __contains__(self, y): # real signature unknown; restored from __doc__
""" x.__contains__(y) <==> y in x. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __ge__(self, *args, **kwargs): # real signature unknown
"""
__ge__=($self, value, /)
-- Return self>=value.
"""
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __iand__(self, *args, **kwargs): # real signature unknown
""" Return self&=value. """
pass def __init__(self, seq=()): # known special case of set.__init__
"""
set() -> new empty set object
set(iterable) -> new set object Build an unordered collection of unique elements.
# (copied from class doc)
"""
pass def __ior__(self, *args, **kwargs): # real signature unknown
""" Return self|=value. """
pass def __isub__(self, *args, **kwargs): # real signature unknown
""" Return self-=value. """
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __ixor__(self, *args, **kwargs): # real signature unknown
""" Return self^=value. """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __or__(self, *args, **kwargs): # real signature unknown
""" Return self|value. """
pass def __rand__(self, *args, **kwargs): # real signature unknown
""" Return value&self. """
pass def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __ror__(self, *args, **kwargs): # real signature unknown
""" Return value|self. """
pass def __rsub__(self, *args, **kwargs): # real signature unknown
""" Return value-self. """
pass def __rxor__(self, *args, **kwargs): # real signature unknown
""" Return value^self. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" S.__sizeof__() -> size of S in memory, in bytes """
pass def __sub__(self, *args, **kwargs): # real signature unknown
""" Return self-value. """
pass def __xor__(self, *args, **kwargs): # real signature unknown
""" Return self^value. """
pass

collections系列

一、计数器(Counter)

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

from collections import Counter

 class Counter(dict):
'''Dict subclass for counting hashable items. Sometimes called a bag
or multiset. Elements are stored as dictionary keys and their counts
are stored as dictionary values.
统计元素的个数,存储在字典中,元素为键,个数为值
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
生成一个计数器,以字典形式存储
>>> c.most_common() # three most common elements
[('a', ), ('b', ), ('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 对所有元素出现的次数求和
>>> c['a'] # count of letter 'a' 统计a出现的次数
>>> for elem in 'shazam': # update counts from an iterable
... c[elem] += # by adding to each element's count
>>> c['a'] # now there are seven 'a' 从一个迭代中更新元素重复的次数,通过加1来改变每个元素重复的次数
>>> del c['b'] # remove all 'b'
>>> c['b'] # now there are zero 'b' 删除计数器中所有的b元素的统计
>>> d = Counter('simsalabim') # make another counter
创建一个新的生成器
>>> c.update(d) # add in the second counter
>>> c['a'] # now there are nine 'a' 将d计数器合并到c生成器
>>> c.clear() # empty the counter
>>> c
Counter()
清空c计数器
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:
如果一个元素的计数被设置为0或者减少到0,则此元素在计数器中仍存在,只是为0而已,
除非使用delete或clear彻底删除
>>> c = Counter('aaabbc')
>>> c['b'] -= # reduce the count of 'b' by two
>>> c.most_common() # 'b' is still in, but its count is zero
[('a', ), ('c', ), ('b', )] '''
# References:
# http://en.wikipedia.org/wiki/Multiset
# http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
# http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
# http://code.activestate.com/recipes/259174/
# Knuth, TAOCP Vol. II section 4.6. def __init__(self, iterable=None, **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': , 'b': }) # a new counter from a mapping
>>> c = Counter(a=, b=) # a new counter from keyword args '''
super().__init__()
self.update(iterable, **kwds) def __missing__(self, key):
'The count of elements not in the Counter is zero.'
# Needed so that self[missing_item] does not raise KeyError
return def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts. >>> Counter('abcdeabcdabcaba').most_common()
[('a', ), ('b', ), ('c', )] '''
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter()) def elements(self):
'''Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC')
>>> sorted(c.elements())
['A', 'A', 'B', 'B', 'C', 'C'] # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
>>> prime_factors = Counter({: , : , : })
>>> product =
>>> for factor in prime_factors.elements(): # loop over factors
... product *= factor # and multiply them
>>> product Note, if an element's count has been set to zero or is a negative
number, elements() will ignore it.
如果元素的数量已经置为0或者负数,则做运算时被忽略
'''
# Emulate Bag.do from Smalltalk and Multiset.begin from C++.
return _chain.from_iterable(_starmap(_repeat, self.items())) # Override dict methods where necessary @classmethod
def fromkeys(cls, iterable, v=None):
# There is no equivalent method for counters because setting v=
# means that no element can have a count greater than one.
raise NotImplementedError(
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') def update(self, iterable=None, **kwds):
'''Like dict.update() but add counts instead of replacing them.
更新,相加:类似dict.update(),但不是替换而是增加计数
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 '''
# The regular dict.update() operation makes no sense here because the
# replace behavior results in the some of original untouched counts
# being mixed-in with all of the other counts for a mismash that
# doesn't have a straight-forward interpretation in most counting
# contexts. Instead, we implement straight-addition. Both the inputs
# and outputs are allowed to contain zero and negative counts. if iterable is not None:
if isinstance(iterable, Mapping):
if self:
self_get = self.get
for elem, count in iterable.items():
self[elem] = count + self_get(elem, )
else:
super().update(iterable) # fast path when counter is empty
else:
_count_elements(self, iterable)
if kwds:
self.update(kwds) def subtract(self, iterable=None, **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.
相减:类似于dict.update(),减去元素的个数统计,而不是替换他们
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'] # in which, minus in witch, minus in watch >>> c['w'] # in which, minus in witch, minus in watch
- '''
if iterable is not None:
self_get = self.get
if isinstance(iterable, Mapping):
for elem, count in iterable.items():
self[elem] = self_get(elem, ) - count
else:
for elem in iterable:
self[elem] = self_get(elem, ) -
if kwds:
self.subtract(kwds) def copy(self):
'Return a shallow copy.'
return self.__class__(self) def __reduce__(self):
return self.__class__, (dict(self),) def __delitem__(self, elem):
'Like dict.__delitem__() but does not raise KeyError for missing values.'
if elem in self:
super().__delitem__(elem) def __repr__(self):
if not self:
return '%s()' % self.__class__.__name__
try:
items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
return '%s({%s})' % (self.__class__.__name__, items)
except TypeError:
# handle case where values are not orderable
return '{0}({1!r})'.format(self.__class__.__name__, dict(self)) # Multiset-style mathematical operations discussed in:
# Knuth TAOCP Volume II section 4.6. exercise
# and at http://en.wikipedia.org/wiki/Multiset
#
# Outputs guaranteed to only include positive counts.
#
# To strip negative and zero counts, add-in an empty counter:
# c += Counter() def __add__(self, other):
'''Add counts from two counters. >>> Counter('abbb') + Counter('bcc')
Counter({'b': , 'c': , 'a': }) '''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count + other[elem]
if newcount > :
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > :
result[elem] = count
return result def __sub__(self, other):
''' Subtract count, but keep only results with positive counts. >>> Counter('abbbc') - Counter('bccd')
Counter({'b': , 'a': }) '''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
newcount = count - other[elem]
if newcount > :
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count < :
result[elem] = - count
return result def __or__(self, other):
'''Union is the maximum of value in either of the input counters. >>> Counter('abbb') | Counter('bcc')
Counter({'b': , 'c': , 'a': }) '''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = other_count if count < other_count else count
if newcount > :
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > :
result[elem] = count
return result def __and__(self, other):
''' Intersection is the minimum of corresponding counts. >>> Counter('abbb') & Counter('bcc')
Counter({'b': }) '''
if not isinstance(other, Counter):
return NotImplemented
result = Counter()
for elem, count in self.items():
other_count = other[elem]
newcount = count if count < other_count else other_count
if newcount > :
result[elem] = newcount
return result def __pos__(self):
'Adds an empty counter, effectively stripping negative and zero counts'
return self + Counter() def __neg__(self):
'''Subtracts from an empty counter. Strips positive and zero counts,
and flips the sign on negative counts. '''
return Counter() - self def _keep_positive(self):
'''Internal method to strip elements with a negative or zero count'''
nonpositive = [elem for elem, count in self.items() if not count > ]
for elem in nonpositive:
del self[elem]
return self def __iadd__(self, other):
'''Inplace add from another counter, keeping only positive counts. >>> c = Counter('abbb')
>>> c += Counter('bcc')
>>> c
Counter({'b': , 'c': , 'a': }) '''
for elem, count in other.items():
self[elem] += count
return self._keep_positive() def __isub__(self, other):
'''Inplace subtract counter, but keep only results with positive counts. >>> c = Counter('abbbc')
>>> c -= Counter('bccd')
>>> c
Counter({'b': , 'a': }) '''
for elem, count in other.items():
self[elem] -= count
return self._keep_positive() def __ior__(self, other):
'''Inplace union is the maximum of value from either counter. >>> c = Counter('abbb')
>>> c |= Counter('bcc')
>>> c
Counter({'b': , 'c': , 'a': }) '''
for elem, other_count in other.items():
count = self[elem]
if other_count > count:
self[elem] = other_count
return self._keep_positive() def __iand__(self, other):
'''Inplace intersection is the minimum of corresponding counts. >>> c = Counter('abbb')
>>> c &= Counter('bcc')
>>> c
Counter({'b': }) '''
for elem, count in self.items():
other_count = other[elem]
if other_count < count:
self[elem] = other_count
return self._keep_positive()

二、有序字典(OrderedDict)

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

from collections import OrderedDict

 class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries. # The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# The sentinel is in self.__hardroot with a weakref proxy in self.__root.
# The prev links are weakref proxies (to prevent circular references).
# Individual links are kept alive by the hard reference in self.__map.
# Those hard references disappear when a key is deleted from an OrderedDict. def __init__(self, *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. '''
if len(args) > :
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__root
except AttributeError:
self.__hardroot = _Link()
self.__root = root = _proxy(self.__hardroot)
root.prev = root.next = root
self.__map = {}
self.__update(*args, **kwds) def __setitem__(self, key, value,
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
self.__map[key] = link = Link()
root = self.__root
last = root.prev
link.prev, link.next, link.key = last, root, key
last.next = link
root.prev = proxy(link)
dict_setitem(self, key, value) def __delitem__(self, key, dict_delitem=dict.__delitem__):
'od.__delitem__(y) <==> del od[y]'
# Deleting an existing item uses self.__map to find the link which gets
# removed by updating the links in the predecessor and successor nodes.
dict_delitem(self, key)
link = self.__map.pop(key)
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev def __iter__(self):
'od.__iter__() <==> iter(od)'
# Traverse the linked list in order.
root = self.__root
curr = root.next
while curr is not root:
yield curr.key
curr = curr.next def __reversed__(self):
'od.__reversed__() <==> reversed(od)'
# Traverse the linked list in reverse order.
root = self.__root
curr = root.prev
while curr is not root:
yield curr.key
curr = curr.prev def clear(self):
'od.clear() -> None. Remove all items from od.'
root = self.__root
root.prev = root.next = root
self.__map.clear()
dict.clear(self) def 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. '''
if not self:
raise KeyError('dictionary is empty')
root = self.__root
if last:
link = root.prev
link_prev = link.prev
link_prev.next = root
root.prev = link_prev
else:
link = root.next
link_next = link.next
root.next = link_next
link_next.prev = root
key = link.key
del self.__map[key]
value = dict.pop(self, key)
return key, value def move_to_end(self, key, last=True):
'''Move an existing element to the end (or beginning if last==False).
将一个已存在的元素移到字典末尾,元素不存在则报错
Raises KeyError if the element does not exist.
When last=True, acts like a fast version of self[key]=self.pop(key). '''
link = self.__map[key]
link_prev = link.prev
link_next = link.next
link_prev.next = link_next
link_next.prev = link_prev
root = self.__root
if last:
last = root.prev
link.prev = last
link.next = root
last.next = root.prev = link
else:
first = root.next
link.prev = root
link.next = first
root.next = first.prev = link def __sizeof__(self):
sizeof = _sys.getsizeof
n = len(self) + # number of links including root
size = sizeof(self.__dict__) # instance dictionary
size += sizeof(self.__map) * # internal dict and inherited dict
size += sizeof(self.__hardroot) * n # link objects
size += sizeof(self.__root) * n # proxy objects
return size update = __update = MutableMapping.update
keys = MutableMapping.keys
values = MutableMapping.values
items = MutableMapping.items
__ne__ = MutableMapping.__ne__ __marker = object() def pop(self, key, default=__marker):
'''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.
删除一个指定的键值,如果键不存在则报错
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default def setdefault(self, key, default=None):
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
如果键不存在,则set[k] = d
if key in self:
return self[key]
self[key] = default
return default @_recursive_repr()
def __repr__(self):
'od.__repr__() <==> repr(od)'
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, list(self.items())) def __reduce__(self):
'Return state information for pickling'
inst_dict = vars(self).copy()
for k in vars(OrderedDict()):
inst_dict.pop(k, None)
return self.__class__, (), inst_dict or None, None, iter(self.items()) def copy(self):
'od.copy() -> a shallow copy of od'
return self.__class__(self) @classmethod
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
If not specified, the value defaults to None. '''
self = cls()
for key in iterable:
self[key] = value
return self def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive. '''
if isinstance(other, OrderedDict):
return dict.__eq__(self, other) and all(map(_eq, self, other))
return dict.__eq__(self, other)

三、默认字典(defaultdict)

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

from collections import defaultdict

 class defaultdict(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.
"""
def copy(self): # real signature unknown; restored from __doc__
""" D.copy() -> a shallow copy of D. """
pass def __copy__(self, *args, **kwargs): # real signature unknown
""" D.copy() -> a shallow copy of D. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __init__(self, default_factory=None, **kwargs): # known case of _collections.defaultdict.__init__
"""
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. # (copied from class doc)
"""
pass def __missing__(self, key): # real signature unknown; restored from __doc__
"""
__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
"""
pass def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass default_factory = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Factory for default value called by __missing__()."""

示例:

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

四、可命名元组(namedtuple)

from collections import namedtuple

五、双向队列(deque)

一个线程安全的双向队列

from collections import deque

 class deque(object):
"""
deque([iterable[, maxlen]]) --> deque object
Build an ordered collection with optimized access from its endpoints.
"""
def append(self, *args, **kwargs): # real signature unknown
""" Add an element to the right side of the deque. """
pass def appendleft(self, *args, **kwargs): # real signature unknown
""" Add an element to the left side of the deque. """
pass def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from the deque. """
pass def count(self, value): # real signature unknown; restored from __doc__
""" D.count(value) -> integer -- return number of occurrences of value """
return def extend(self, *args, **kwargs): # real signature unknown
""" Extend the right side of the deque with elements from the iterable """
使用迭代中的元素扩展队列的右侧
pass def extendleft(self, *args, **kwargs): # real signature unknown
""" Extend the left side of the deque with elements from the iterable """
pass def pop(self, *args, **kwargs): # real signature unknown
""" Remove and return the rightmost element. """
pass def popleft(self, *args, **kwargs): # real signature unknown
""" Remove and return the leftmost element. """
pass def remove(self, value): # real signature unknown; restored from __doc__
""" D.remove(value) -- remove first occurrence of value. """
pass def reverse(self): # real signature unknown; restored from __doc__
""" D.reverse() -- reverse *IN PLACE* """
反转队列
pass def rotate(self, *args, **kwargs): # real signature unknown
""" Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. """
旋转队列
pass def __copy__(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a deque. """
pass def __delitem__(self, *args, **kwargs): # real signature unknown
""" Delete self[key]. """
pass def __eq__(self, *args, **kwargs): # real signature unknown
""" Return self==value. """
pass def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass def __getitem__(self, *args, **kwargs): # real signature unknown
""" Return self[key]. """
pass def __ge__(self, *args, **kwargs): # real signature unknown
"""
__ge__=($self, value, /)
-- Return self>=value.
"""
pass def __gt__(self, *args, **kwargs): # real signature unknown
""" Return self>value. """
pass def __iadd__(self, *args, **kwargs): # real signature unknown
""" Implement self+=value. """
pass def __init__(self, iterable=(), maxlen=None): # known case of _collections.deque.__init__
"""
deque([iterable[, maxlen]]) --> deque object Build an ordered collection with optimized access from its endpoints.
# (copied from class doc)
"""
pass def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass def __len__(self, *args, **kwargs): # real signature unknown
""" Return len(self). """
pass def __le__(self, *args, **kwargs): # real signature unknown
""" Return self<=value. """
pass def __lt__(self, *args, **kwargs): # real signature unknown
""" Return self<value. """
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __ne__(self, *args, **kwargs): # real signature unknown
""" Return self!=value. """
pass def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass def __reversed__(self): # real signature unknown; restored from __doc__
""" D.__reversed__() -- return a reverse iterator over the deque """
pass def __setitem__(self, *args, **kwargs): # real signature unknown
""" Set self[key] to value. """
pass def __sizeof__(self): # real signature unknown; restored from __doc__
""" D.__sizeof__() -- size of D in memory, in bytes """
pass maxlen = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""maximum size of a deque or None if unbounded""" __hash__ = None

六、单向队列(queue.queue)

先进先出

待叙。。。。。

												

python数据类型之 set的更多相关文章

  1. python 数据类型---布尔型& 字符串

    python数据类型-----布尔型 真或假=>1或0 >>> 1==True True >>> 0==False True python 数据类型----- ...

  2. Python 数据类型及其用法

    本文总结一下Python中用到的各种数据类型,以及如何使用可以使得我们的代码变得简洁. 基本结构 我们首先要看的是几乎任何语言都具有的数据类型,包括字符串.整型.浮点型以及布尔类型.这些基本数据类型组 ...

  3. day01-day04总结- Python 数据类型及其用法

    Python 数据类型及其用法: 本文总结一下Python中用到的各种数据类型,以及如何使用可以使得我们的代码变得简洁. 基本结构 我们首先要看的是几乎任何语言都具有的数据类型,包括字符串.整型.浮点 ...

  4. Python数据类型及其方法详解

    Python数据类型及其方法详解 我们在学习编程语言的时候,都会遇到数据类型,这种看着很基础也不显眼的东西,却是很重要,本文介绍了python的数据类型,并就每种数据类型的方法作出了详细的描述,可供知 ...

  5. Python学习笔记(五)--Python数据类型-数字及字符串

    Python数据类型:123和'123'一样吗?>>> 123=='123'False>>> type(123)<type 'int'>>> ...

  6. python数据类型之元组、字典、集合

    python数据类型元组.字典.集合 元组 python的元组与列表类似,不同的是元组是不可变的数据类型.元组使用小括号,列表使用方括号.当元组里只有一个元素是必须要加逗号: >>> ...

  7. 1 Python数据类型--

    常见的Python数据类型: (1)数值类型:就是平时处理的数字(整数.浮点数) (2)序列类型:有一系列的对象并排或者排列的情况.如字符串(str),列表(list),元组(tuple)等 (3)集 ...

  8. Python数据类型和数据操作

    python数据类型有:int,float,string,boolean类型.其中string类型是不可变变量,用string定义的变量称为不可变变量,该变量的值不能修改. 下面介绍python中的l ...

  9. Python数据类型(python3)

    Python数据类型(python3) 基础数据类型 整型 <class 'int'> 带符号的,根据机器字长32位和64位表示的范围不相同,分别是: -2^31 - 2^31-1 和 - ...

  10. 二、Python数据类型(一)

    一.Python的基本输入与输出语句 (一)输出语句 print() 示例: print('你好,Python') print(4+5) a = 10 print(a) 输出的内容可以是字符串,变量, ...

随机推荐

  1. Android点击View显示PopupWindow,再次重复点击View关闭PopupWindow

     Android点击View显示PopupWindow,再次重复点击View关闭PopupWindow 这本身是一个看似很简单的问题,但是如果设置不当,就可能导致莫名其妙失效问题.通常在Andro ...

  2. 解决CSS小于12px的文字在谷歌浏览器显示问题

    做前端设计的人经常要接触CSS方面的问题,估计有不少人会遇到Chrome谷歌浏览器中CSS设置字体小于12px显示不正常,强创网络在做magento模板过程中就遇到了,起初以为是自己写的CSS的问题, ...

  3. 第一个Sprint冲刺事后诸葛报告

    用户反馈:软件一般般,比较传统. 用户数量:5 团队改进建议:选择题与填空题太没有新意了,需要新的创新功能. 1.每个成员第一个sprint阶段有何需要改进? 成员 需要改进 邵家文 需要更多的技术的 ...

  4. eval函数的工作原理

    如果您想详细了解eval和JSON请参考以下链接: eval  :https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Glob ...

  5. 转:【More Effective C#】Lambda表达式优化

    http://www.cnblogs.com/kongyiyun/archive/2010/10/19/1855274.html 使用Lambda表达式将会造成Lambda表达式主题部分的代码重复. ...

  6. 用 CSS 实现字符串截断

    [要求]:如何用css实现字符串截断,超出约定长度后用缩略符...代替?   ♪ 答: <html> <head> <meta charset="UTF-8&q ...

  7. Shell字符串截取

    shell中截取字符串的方法有很多中, ${expression}一共有9种使用方法. ${parameter:-word} ${parameter:=word} ${parameter:?word} ...

  8. android获取inflater

    LayoutInflater作用是将layout的xml布局文件实例化为View类对象. 获取LayoutInflater的方法有如下三种: ? LayoutInflater inflater=(La ...

  9. iOS学习笔记---oc语言第二天

    实例变量与方法 一.实例变量的可见度 二.方法 oc中的方法分两种:类方法和实例方法 类方法:只能类使用 eg:+ (id)alloc  注:类方法中不能使用实例变量 实例方法:只能对象使用,eg:- ...

  10. ZOJ 1005 Jugs

    原题链接 题目大意:有一大一小两个杯子,相互倒水,直到其中一个杯子里剩下特定体积的水.描述这个过程. 解法:因为两个杯子的容积互质,所以只要用小杯子不断往大杯子倒水,大杯子灌满后就清空,大杯子里迟早会 ...