python数据类型之 set
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的更多相关文章
- python 数据类型---布尔型& 字符串
python数据类型-----布尔型 真或假=>1或0 >>> 1==True True >>> 0==False True python 数据类型----- ...
- Python 数据类型及其用法
本文总结一下Python中用到的各种数据类型,以及如何使用可以使得我们的代码变得简洁. 基本结构 我们首先要看的是几乎任何语言都具有的数据类型,包括字符串.整型.浮点型以及布尔类型.这些基本数据类型组 ...
- day01-day04总结- Python 数据类型及其用法
Python 数据类型及其用法: 本文总结一下Python中用到的各种数据类型,以及如何使用可以使得我们的代码变得简洁. 基本结构 我们首先要看的是几乎任何语言都具有的数据类型,包括字符串.整型.浮点 ...
- Python数据类型及其方法详解
Python数据类型及其方法详解 我们在学习编程语言的时候,都会遇到数据类型,这种看着很基础也不显眼的东西,却是很重要,本文介绍了python的数据类型,并就每种数据类型的方法作出了详细的描述,可供知 ...
- Python学习笔记(五)--Python数据类型-数字及字符串
Python数据类型:123和'123'一样吗?>>> 123=='123'False>>> type(123)<type 'int'>>> ...
- python数据类型之元组、字典、集合
python数据类型元组.字典.集合 元组 python的元组与列表类似,不同的是元组是不可变的数据类型.元组使用小括号,列表使用方括号.当元组里只有一个元素是必须要加逗号: >>> ...
- 1 Python数据类型--
常见的Python数据类型: (1)数值类型:就是平时处理的数字(整数.浮点数) (2)序列类型:有一系列的对象并排或者排列的情况.如字符串(str),列表(list),元组(tuple)等 (3)集 ...
- Python数据类型和数据操作
python数据类型有:int,float,string,boolean类型.其中string类型是不可变变量,用string定义的变量称为不可变变量,该变量的值不能修改. 下面介绍python中的l ...
- Python数据类型(python3)
Python数据类型(python3) 基础数据类型 整型 <class 'int'> 带符号的,根据机器字长32位和64位表示的范围不相同,分别是: -2^31 - 2^31-1 和 - ...
- 二、Python数据类型(一)
一.Python的基本输入与输出语句 (一)输出语句 print() 示例: print('你好,Python') print(4+5) a = 10 print(a) 输出的内容可以是字符串,变量, ...
随机推荐
- Unity3D入门(一):环境搭建
1.Unity3D 目前最新正式版本是4.2.1f 官网下载,以前的版本安装时候需要序列号激活,新版本4.2.1f 不需要,完全免费,但发布的时候需要许可证 2.要学习的同学,下载频道可以找到破解补 ...
- iBatis框架简介
一.为啥使用iBatis? 在 Hibernate.JPA 这样的一站式对象 / 关系映射(O/R Mapping)解决方案盛行之前,iBaits 基本是持久层框架的不二选择.即使在持久层框架层出不穷 ...
- java zip文件的解压缩(支持中文文件名)
用的apache的ant包,下载导入即可.由于过程比较简单,直接上代码. 代码可直接复制使用. 如果想在android上使用,记得要在AndroidManifest.xml里添加权限: <use ...
- 尽量多的以 const/enum/inline 替代 #define
前言 在面向过程语言,如 C 语言中,#define 非常常见,也确实好用,值得提倡.但在如今面向对象的语言,如 C++ 语言中,#define 就要尽量少用了. 为何在 C++ 中就要少用了呢? 这 ...
- 图像处理之face morphing
以前在论坛.微博经常看到一张脸,五官长得像A,脸型似乎又是B,觉得很有意思. 比如像这张图片.这张图片应该是网友用Photoshop完成的,他们取了郭大爷的五官,放在金元帅的脸上,在把边缘处理平滑. ...
- c++函数重载---2
原创博客:转载请标明出处:http://www.cnblogs.com/zxouxuewei/ 写在前面: 函数重载的重要性不言而明,但是你知道C++中函数重载是如何实现的呢(虽然本文谈的是C++中函 ...
- Java动物声音模拟器
abstract class Animal{ abstract void cry(); abstract String getAnimalName(); } class Simulator{ void ...
- ArrayList线程不安全
ArrayList线程不安全分析 http://wsmajunfeng.iteye.com/blog/1493941 一个 ArrayList ,在添加一个元素的时候,它可能会有两步来完成:1. ...
- php构造函数实例讲解
PHP官网定义: 复制代码 代码如下: 构造函数是类中的一个特殊函数,当使用 new 操作符创建一个类的实例时,构造函数将会自动调用.当函数与类同名时,这个函数将成为构造函数.如果一个类没有构造函数, ...
- ExtJS控件样式修改及美化
Extjs项目对富客户端开发提供了强有力的支持,甚至改变了前端的开发方式,使得开发变得更加趋向于“面向组件”.对界面的美化而言,也是根本性的改变.普通的网页美工面对extjs项目根本无法下手,需要脚本 ...