collection模块是对python的通用内置容器:字典、列表、元组和集合的扩展,它包含一些专业的容器数据类型:
counter(计数器):dict子类,用于计算可哈希性对象的个数。
ordereddict(有序字典):dict 子类,记录着数据成员添加的顺序。
defaultdict(默认字典):dict 子类,调用一个工厂函数来为dict的values值缺失提供一个默认值。
namedtuple(可命名元组):工厂函数生成有命名字段的tuple子类。
deque(双向队列):能在“队列”两端快速出队、入队的函数,类似于队列的(list-like)的容器。
chainmap:为多个映射创建单一视图的类字典类型。
userdict:将字典包裹起来使得创建字典的子类更容易。
userlist:将列表对象包裹起来使得创建列表的子类更容易。
userstring:将字符串对象包裹起来使得创建字符串的子类更容易。
1.计数器(counter)
counter是dict的子类,用于计数可哈希性对象。它是一个无序的容器,元素存储为字典键,计数值存储为字典值。计数允许任何整数值,包括零或负计数。counter类相似于bags或multisets等语言类。
它的元素从一个可迭代对象计数,或从另一个映射(或计数器)初始化。
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(3) # three most common elements
[(‘a’, 5), (‘b’, 4), (‘c’, 3)]
>>> sorted(c) # list all unique elements
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
>>> ”.join(sorted(c.elements())) # list elements with repetitions
‘aaaaabbbbcccdde’
>>> sum(c.values()) # total of all counts
15
>>> c[‘a’] # count of letter ‘a’
5
>>> for elem in ‘shazam’: # update counts from an iterable
… c[elem] += 1 # by adding 1 to each element’s count
>>> c[‘a’] # now there are seven ‘a’
7
>>> del c[‘b’] # remove all ‘b’
>>> c[‘b’] # now there are zero ‘b’
0
>>> d = counter(‘simsalabim’) # make another counter
>>> c.update(d) # add in the second counter
>>> c[‘a’] # now there are nine ‘a’
9
>>> c.clear() # empty the counter
>>> c
counter()
note: if a count is set to zero or reduced to zero, it will remain
in the counter until the entry is deleted or the counter is cleared:
>>> c = counter(‘aaabbc’)
>>> c[‘b’] -= 2 # reduce the count of ‘b’ by two
>>> c.most_common() # ‘b’ is still in, but its count is zero
[(‘a’, 3), (‘c’, 1), (‘b’, 0)]
”’
# references:
# http://en.wikipedia.org/wiki/multiset
# http://www.gnu.org/software/smalltalk/manual-base/html_node/bag.html
# http://www.demo2s.com/tutorial/cpp/0380set-multiset/catalog0380set-multiset.htm
# http://code.activestate.com/recipes/259174/
# knuth, taocp vol. ii section 4.6.3
def init(*args, **kwds):
”’create a new, empty counter object. and if given, count elements
from an input iterable. or, initialize the count from another mapping
of elements to their counts.
>>> c = counter() # a new, empty counter
>>> c = counter(‘gallahad’) # a new counter from an iterable
>>> c = counter({‘a’: 4, ‘b’: 2}) # a new counter from a mapping
>>> c = counter(a=4, b=2) # a new counter from keyword args
”’
if not args:
raise typeerror(“descriptor ‘init’ of ‘counter’ object ”
“needs an argument”)
self, *args = args
if len(args) > 1:
raise typeerror(‘expected at most 1 arguments, got %d’ % len(args))
super(counter, self).init()
self.update(*args, **kwds)
def missing(self, key):
‘the count of elements not in the counter is zero.’
# needed so that self[missing_item] does not raise keyerror
return 0
def most_common(self, n=none):
”’list the n most common elements and their counts from the most
common to the least. if n is none, then list all element counts.
>>> counter(‘abcdeabcdabcaba’).most_common(3)
[(‘a’, 5), (‘b’, 4), (‘c’, 3)]
”’
# emulate bag.sortedbycount from smalltalk
if n is none:
return sorted(self.items(), key=_itemgetter(1), reverse=true)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
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({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.
”’
# 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=1
# means that no element can have a count greater than one.
raise notimplementederror(
‘counter.fromkeys() is undefined. use counter(iterable) instead.’)
def update(*args, **kwds):
”’like dict.update() but add counts instead of replacing them.
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
”’
# the regular dict.update() operation makes no sense here because the
# replace behavior results in the some of original untouched counts
# being mixed-in with all of the other counts for a mismash that
# doesn’t have a straight-forward interpretation in most counting
# contexts. instead, we implement straight-addition. both the inputs
# and outputs are allowed to contain zero and negative counts.
if not args:
raise typeerror(“descriptor ‘update’ of ‘counter’ object ”
“needs an argument”)
self, *args = args
if len(args) > 1:
raise typeerror(‘expected at most 1 arguments, got %d’ % len(args))
iterable = args[0] if args else none
if iterable is not none:
if isinstance(iterable, mapping):
if self:
self_get = self.get
for elem, count in iterable.items():
self[elem] = count + self_get(elem, 0)
else:
super(counter, self).update(iterable) # fast path when counter is empty
else:
_count_elements(self, iterable)
if kwds:
self.update(kwds)
def subtract(*args, **kwds):
”’like dict.update() but subtracts counts instead of replacing them.
counts can be reduced below zero. both the inputs and outputs are
allowed to contain zero and negative counts.
source can be an iterable, a dictionary, or another counter instance.
>>> c = counter(‘which’)
>>> c.subtract(‘witch’) # subtract elements from another iterable
>>> c.subtract(counter(‘watch’)) # subtract elements from another counter
>>> c[‘h’] # 2 in which, minus 1 in witch, minus 1 in watch
0
>>> c[‘w’] # 1 in which, minus 1 in witch, minus 1 in watch
-1
”’
if not args:
raise typeerror(“descriptor ‘subtract’ of ‘counter’ object ”
“needs an argument”)
self, *args = args
if len(args) > 1:
raise typeerror(‘expected at most 1 arguments, got %d’ % len(args))
iterable = args[0] if args else none
if iterable is not none:
self_get = self.get
if isinstance(iterable, mapping):
for elem, count in iterable.items():
self[elem] = self_get(elem, 0) – count
else:
for elem in iterable:
self[elem] = self_get(elem, 0) – 1
if kwds:
self.subtract(kwds)
def copy(self):
‘return a shallow copy.’
return self.class(self)
def reduce(self):
return self.class, (dict(self),)
def delitem(self, elem):
‘like dict.delitem() but does not raise keyerror for missing values.’
if elem in self:
super().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.3 exercise 19
# and at http://en.wikipedia.org/wiki/multiset
#
# outputs guaranteed to only include positive counts.
#
# to strip negative and zero counts, add-in an empty counter:
# c += counter()
def add(self, other):
”’add counts from two counters.
>>> counter(‘abbb’) + counter(‘bcc’)
counter({‘b’: 4, ‘c’: 2, ‘a’: 1})
”’
if not isinstance(other, counter):
return notimplemented
result = counter()
for elem, count in self.items():
newcount = count + other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
def sub(self, other):
”’ subtract count, but keep only results with positive counts.
>>> counter(‘abbbc’) – counter(‘bccd’)
counter({‘b’: 2, ‘a’: 1})
”’
if not isinstance(other, counter):
return notimplemented
result = counter()
for elem, count in self.items():
newcount = count – other[elem]
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count < 0:
result[elem] = 0 - count
return result
def or(self, other):
'''union is the maximum of value in either of the input counters.
>>> counter(‘abbb’) | counter(‘bcc’)
counter({‘b’: 3, ‘c’: 2, ‘a’: 1})
”’
if not isinstance(other, counter):
return notimplemented
result = counter()
for elem, count in self.items():
other_count = other[elem]
newcount = other_count if count < other_count else count
if newcount > 0:
result[elem] = newcount
for elem, count in other.items():
if elem not in self and count > 0:
result[elem] = count
return result
def and(self, other):
”’ intersection is the minimum of corresponding counts.
>>> counter(‘abbb’) & counter(‘bcc’)
counter({‘b’: 1})
”’
if not isinstance(other, counter):
return notimplemented
result = counter()
for elem, count in self.items():
other_count = other[elem]
newcount = count if count < other_count else other_count
if newcount > 0:
result[elem] = newcount
return result
def pos(self):
‘adds an empty counter, effectively stripping negative and zero counts’
result = counter()
for elem, count in self.items():
if count > 0:
result[elem] = count
return result
def neg(self):
”’subtracts from an empty counter. strips positive and zero counts,
and flips the sign on negative counts.
”’
result = counter()
for elem, count in self.items():
if count < 0:
result[elem] = 0 - count
return result
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 > 0]
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’: 4, ‘c’: 2, ‘a’: 1})
”’
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’: 2, ‘a’: 1})
”’
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’: 3, ‘c’: 2, ‘a’: 1})
”’
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’: 1})
”’
for elem, count in self.items():
other_count = other[elem]
if other_count < count:
self[elem] = other_count
return self._keep_positive()
counter
1)计数器的创建:
from collections import counter #counter 需要申明
a=counter() # 创建空计数器
b=counter(‘aabbbcccc’) # 可迭代对象计数的方式创建对象
c = counter({‘red’: 4, ‘blue’: 2}) # 映射方法创建计数器
d = counter(cats=4, dogs=8) # 键值的方法创建计数器
2)计数器元素的删除
a=counter({‘a’:2,’b’:6,’c’:4,’d’:0,’e’:-2})
print(a)
a[‘a’]=0 #修改了计数器元素里的值
print(a)
del a[‘b’] #删除了元素
print(a)
#运行结果
counter({‘b’: 6, ‘c’: 4, ‘a’: 2, ‘d’: 0, ‘e’: -2})
counter({‘b’: 6, ‘c’: 4, ‘a’: 0, ‘d’: 0, ‘e’: -2})
counter({‘c’: 4, ‘a’: 0, ‘d’: 0, ‘e’: -2})
del
3)计数器的部分功能属性
most_common(self, n=none):
把计数器转化成列表,元素转化成元组,返回n个最常见的元素及其计数的列表,从最常见到最少见。如果省略n或为none,most_common()返回计数器中所有元素。具有相等计数的元素是任意排序的。
a=counter({‘a’:2,’b’:6,’c’:4,’d’:0,’e’:-2})
b=a.most_common()
c=a.most_common(2)
print(a)
print(b,type(b))
print(c,type(c))
#运行结果
counter({‘b’: 6, ‘c’: 4, ‘a’: 2, ‘d’: 0, ‘e’: -2})
[(‘b’, 6), (‘c’, 4), (‘a’, 2), (‘d’, 0), (‘e’, -2)]
[(‘b’, 6), (‘c’, 4)]
demo
elements(self):
返回一个迭代器,对元素重复迭代其计数次。元素以随机顺序返回。如果元素的计数小于1,elements()将忽略它。
a=counter({‘a’:2,’b’:6,’c’:4,’d’:0,’e’:-2})
b=a.elements()
c=sorted(a.elements())
print(a)
print(b,type(b))
print(c,type(c))
#运行结果
counter({‘b’: 6, ‘c’: 4, ‘a’: 2, ‘d’: 0, ‘e’: -2})
[‘a’, ‘a’, ‘b’, ‘b’, ‘b’, ‘b’, ‘b’, ‘b’, ‘c’, ‘c’, ‘c’, ‘c’]
demo
update(*args, **kwds):
元素从一个可迭代对象计数或从另一个映射(或计数器)增加。类似dict.update(),但增加计数,而不是替换它们。此外,可迭代对象应为一系列元素,而不是(key, value)对。
a=counter({‘a’:2,’b’:6,’c’:4,’d’:0,’e’:-2})
a.update(‘abe’)
a.update({‘g’:1})
print(a)
#运行结果
counter({‘b’: 7, ‘c’: 4, ‘a’: 3, ‘g’: 1, ‘d’: 0, ‘e’: -1})
demo
subtract(*args, **kwds):从一个可迭代对象或另一个映射(或计数器)中减去元素。类似dict.update(),但减去计数,而不是替换它们。输入和输出都可以为零或负。
a=counter({‘a’:2,’b’:6,’c’:4,’d’:0,’e’:-2})
a.subtract(‘ade’)
print(a)
#运行结果
counter({‘b’: 6, ‘c’: 4, ‘a’: 1, ‘d’: -1, ‘e’: -3})
demo
2.有序字典(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).
# inpidual 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(*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 not args:
raise typeerror(“descriptor ‘init’ of ‘ordereddict’ object ”
“needs an argument”)
self, *args = args
if len(args) > 1:
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
link.prev = none
link.next = none
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) + 1 # number of links including root
size = sizeof(self.dict) # instance dictionary
size += sizeof(self.map) * 2 # 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
def keys(self):
“d.keys() -> a set-like object providing a view on d’s keys”
return _ordereddictkeysview(self)
def items(self):
“d.items() -> a set-like object providing a view on d’s items”
return _ordereddictitemsview(self)
def values(self):
“d.values() -> an object providing a view on d’s values”
return _ordereddictvaluesview(self)
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’
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)
try:
from _collections import ordereddict
except importerror:
# leave the pure python version in place.
pass
ordereddict
1)有序字典的创建:
from collections import ordereddict
a=dict() #
b=ordereddict()
a[‘a’]=1
a[‘b’]=2
a[‘c’]=3
a[‘d’]=4
b[‘a’]=1
b[‘b’]=2
b[‘c’]=3
b[‘d’]=4
print(a,type(a))
print(b,type(b))
#运行结果
{‘a’: 1, ‘c’: 3, ‘d’: 4, ‘b’: 2}
ordereddict([(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4)])
demo
2)有序字典的功能:有序字典继承了字典的功能,下面只介绍与字典不同功能。popitem(self, last=true):返回并删除字典中的键值对。如果last为true(默认值),则以lifo顺序返回这些键值对,如果为false,则以fifo顺序返回。
a=ordereddict()
a[‘a’]=1
a[‘b’]=2
a[‘c’]=3
a[‘d’]=4
b=a.popitem()
print(a)
print(b)
#运行结果
ordereddict([(‘a’, 1), (‘b’, 2), (‘c’, 3)])
(‘d’, 4)
demo
move_to_end(self, key, last=true):将一个已存在key移动到有序字典的另一端。如果last为true(默认值),则项目移动到末尾,如果last为false,则移动到开始。如果key不存在,引发keyerror。
a=ordereddict()
a[‘a’]=1
a[‘b’]=2
a[‘c’]=3
a[‘d’]=4
print(a)
b=a.move_to_end(‘b’)
print(a)
#运行结果
ordereddict([(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4)])
ordereddict([(‘a’, 1), (‘c’, 3), (‘d’, 4), (‘b’, 2)])
demo
3.默认字典(defaultdict) defaultdict可以把字典指定一个默认value,可以是字典/列表等。返回一个新的类似字典的对象,功能与dict类相同。如:
from collections import defaultdict
a=defaultdict(list) #默认value为list
b=defaultdict(tuple) #默认value为tuple
c=defaultdict(dict) #默认value为dict
d=dict()
print(a)
print(b)
print(c)
print(d)
#运行结果
defaultdict(, {})
defaultdict(, {})
defaultdict(, {})
{}
demo
应用:
s = [(‘yellow’, 1), (‘blue’, 2), (‘yellow’, 3), (‘blue’, 4), (‘red’, 1)]
d = defaultdict(list)
for k, v in s:
d[k].append(v) #如果使用普通字典,需要先给字典初始化键值对
c=sorted(d.items())
print(type(s))
print(d)
print(c,type(c))
#运行结果
defaultdict(, {‘red’: [1], ‘blue’: [2, 4], ‘yellow’: [1, 3]})
[(‘blue’, [2, 4]), (‘red’, [1]), (‘yellow’, [1, 3])]
demo
默认字典的功能:
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().”””
defaultdict
4.可命名元组(namedtuple)
1)可命名元组的说明
给元组中每个位置上的元素命名,它们可以使用常规的元组方法,可以让访问元素可以按名称而不是按位置索引。
collections.namedtuple(typename, field_names, verbose=false, rename=false):
返回一个叫做 typename 的tuple子类,这个新的子类用来创建类tuple(tuple-like)的对象,这个对象拥有可以通过属性访问的字段,并且可以通过下标索引和迭代。
field_names 是一个单独的字符串,这个字符串中包含的所有字段用空格或逗号隔开,例如 ‘xy’ 或 ‘x,y’.另外, field_names 也可以是字符串的列表,例如 [‘x’, ‘y’]。
如果verbose 为 true, 在类被建立后将打印类的定义。相反,它打印的是类的 _source 属性,也就是打印源代码。
如果 rename参数 为 true, 无效的field_names会被自动转换成位置的名称.例如, [‘abc’, ‘def’, ‘ghi’, ‘abc’] 将被转换为 [‘abc’, ‘_1’, ‘ghi’, ‘_3’], 来消除关键字 def 和重复的字段名 abc。
2)可命名元组的创建
需要先创建一个类。
from collections import namedtuple
mytuplemytupleclass’,[‘x’,’y’])
a=point(1,2)
b=point(2,0)
print(a,a.x,a.y,type(a))
print(b,b.x,b.y,type(b))
#运行结果
mytupleclass(x=1, y=2) 1 2
mytupleclass(x=2, y=0) 2 0
3)可命名元组新创建类的功能属性
如上面创建的mytuplecalss类:
print(help(mytupleclass)) #运行help打印获取
class mytupleclass(builtins.tuple)
| mytupleclass(x, y)
|
| method resolution order:
| mytupleclass
| builtins.tuple
| builtins.object
|
| methods defined here:
|
| getnewargs(self)
| return self as a plain tuple. used by copy and pickle.
|
| repr(self)
| return a nicely formatted representation string
|
| _asdict(self)
| return a new ordereddict which maps field names to their values.
|
| _replace(_self, **kwds)
| return a new mytupleclass object replacing specified fields with new values
|
| ———————————————————————-
| class methods defined here:
|
| _make(iterable, new=, len=) from builtins.type
| make a new mytupleclass object from a sequence or iterable
|
| ———————————————————————-
| static methods defined here:
|
| new(_cls, x, y)
| create new instance of mytupleclass(x, y)
|
| ———————————————————————-
| data descriptors defined here:
|
| x
| alias for field number 0
|
| y
| alias for field number 1
|
| ———————————————————————-
| data and other attributes defined here:
|
| _fields = (‘x’, ‘y’)
|
| _source = “from builtins import property as _property, tupl…_itemget…
|
| ———————————————————————-
| methods inherited from builtins.tuple:
|
| add(self, value, /)
| return self+value.
|
| contains(self, key, /)
| return key in self.
|
| eq(self, value, /)
| return self==value.
|
| ge(self, value, /)
| return self>=value.
|
| getattribute(self, name, /)
| return getattr(self, name).
|
| getitem(self, key, /)
| return self[key].
|
| gt(self, value, /)
| return self>value.
|
| hash(self, /)
| return hash(self).
|
| iter(self, /)
| implement iter(self).
|
| le(self, value, /)
| return self integer — return first index of value.
| raises valueerror if the value is not present.
none
mytuplecalss
5.队列(deque)
1)双向队列(deque)
双向队列(deque)是栈和队列的一般化。可以在两端添加和删除元素。
双向队列的创建:
from collections import deque
a=deque()
b=deque(‘abcd’)
print(a,type(a))
print(b,type(b))
#运行结果
deque([])
deque([‘a’, ‘b’, ‘c’, ‘d’])
双向队列的功能属性:
class deque(object):
“””
deque([iterable[, maxlen]]) –> deque object
a list-like sequence optimized for data accesses near 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 copy(self, *args, **kwargs): # real signature unknown
“”” return a shallow copy of a deque. “””
pass
def count(self, value): # real signature unknown; restored from doc
“”” d.count(value) -> integer — return number of occurrences of value “””
return 0
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 index(self, value, start=none, stop=none): # real signature unknown; restored from doc
“””
d.index(value, [start, [stop]]) -> integer — return first index of value.
raises valueerror if the value is not present.
“””
return 0
def insert(self, index, p_object): # real signature unknown; restored from doc
“”” d.insert(index, object) — insert object before index “””
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 add(self, *args, **kwargs): # real signature unknown
“”” return self+value. “””
pass
def bool(self, *args, **kwargs): # real signature unknown
“”” self != 0 “””
pass
def contains(self, *args, **kwargs): # real signature unknown
“”” return key in self. “””
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
“”” 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 imul(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
a list-like sequence optimized for data accesses near 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