#namedtuple()
factory function for creating tuple subclasses with named fields
|
|
#deque
list-like container with fast appends and pops on either end.
It is short for “double-ended queue”. Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.
|
|
#Counter
dict subclass for counting hashable objects.
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.
#初始化方法
|
|
#常用方法
-
elements()
requires integer counts. It ignores zero and negative counts. Return an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary(随意的) order. -
most_common([n])
Return a list of the n most common elements and their counts from the most common to the least. Elements with equal counts are ordered arbitrarily. -
subtract([iterable-or-mapping])
1 2 3 4 5 6 7 8
c5 = Counter({'a': 1, 'b': 2, 'c': 3, 'd': 4}) c6 = Counter({'a': -4, 'b': 2, 'c': 1, 'e': 4}) c5.subtract(c6) print(c5) # Counter({'a': 5, 'd': 4, 'c': 2, 'b': 0, 'e': -4}) # 在c5中e的计数为0,把Counter中的一个元素的值设为0并没有把这个元素从Counter中移除,要真正的移除使用del c['a'] # print(c5 - c6) # Counter({'a': 5, 'd': 4, 'c': 2}) # 直接使用减号是将c5中与c6中键值都相同的元素删除,键相同值不同的元素值相减
-
update()
1 2 3 4 5
c5 = Counter({'a': 1, 'b': 2, 'c': 3, 'd': 4}) c6 = Counter({'a': -4, 'b': 2, 'c': 1, 'e': 4}) c5.update(c6) print(c5) # Counter({'b': 4, 'c': 4, 'd': 4, 'e': 4, 'a': -3})
-
Others
1 2 3 4 5 6 7 8 9 10
>>> c = Counter(a=3, b=1) >>> d = Counter(a=1, b=2) >>> c + d # add two counters together: c[x] + d[x] Counter({'a': 4, 'b': 3}) >>> c - d # subtract (keeping only positive counts) Counter({'a': 2}) >>> c & d # intersection: min(c[x], d[x]) # doctest: +SKIP Counter({'a': 1, 'b': 1}) >>> c | d # union: max(c[x], d[x]) Counter({'a': 3, 'b': 2})
#OrderedDict
dict subclass that remembers the order entries were added.
|
|
-
popitem(last=True)
The popitem() method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false.
-
move_to_end(key, last=True)
Move an existing key to either end of an ordered dictionary. The item is moved to the right end if last is true (the default) or to the beginning if last is false. Raises KeyError if the key does not exist.
1 2 3 4 5 6 7
>>> d = OrderedDict.fromkeys('abcde') >>> d.move_to_end('b') >>> ''.join(d.keys()) 'acdeb' >>> d.move_to_end('b', last=False) >>> ''.join(d.keys()) 'bacde'