Collections module
In [1]:
from collections import *
In [4]:
c1 = Counter()
c2 = Counter('gaufung')
c3 = Counter({'red':4,'blue':10})
c4 = Counter(cats=4,dogs=5)
In [8]:
c = Counter(['dog', 'cat'])
c['fox']
Out[8]:
In [13]:
c['dog'] = 0
del c['dog']
In [14]:
c = Counter(a=4, b=2, c=0, d=-2)
print list(c.elements())
In [16]:
Counter('abracadabra').most_common(3)
Out[16]:
In [17]:
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
c
Out[17]:
append(x)
Add x to the right side of the deque.
appendleft(x)
Add x to the left side of the deque.
clear()
Remove all elements from the deque leaving it with length 0.
count(x)
Count the number of deque elements equal to x.
extend(iterable)
Extend the right side of the deque by appending elements from the iterable argument.
extendleft(iterable)
Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.
pop()
Remove and return an element from the right side of the deque. If no elements are present, raises an IndexError.
popleft()
Remove and return an element from the left side of the deque. If no elements are present, raises an IndexError.
remove(value)
Removed the first occurrence of value. If not found, raises a ValueError.
reverse()
Reverse the elements of the deque in-place and then return None.
rotate(n)
Rotate the deque n steps to the right. If n is negative, rotate to the left. Rotating one step to the right is equivalent to: d.appendleft(d.pop()).
maxlen
Maximum size of a deque or None if unbounded.
dictionary supply missing values
In [18]:
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
d[k].append(v)
d.items()
Out[18]:
Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.
namedtuple(typename, field_names[, verbose=False][, rename=False])
In [19]:
Point = namedtuple('Point', ['x', 'y'], verbose=True)
In [20]:
p = Point(11, y=22)
p
Out[20]:
Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted.