Python Tutorial

Showing posts with label collections. Show all posts
Showing posts with label collections. Show all posts

Tuesday, February 19, 2013

Python collections - Counter

Counter is used for counting hashable object.

All source code available on github

from collections import Counter

a=[1,2,3,4,2,3,4,45,4,7,8]
counter = Counter(a)

print counter
print counter.values()
print counter.keys()


Output:
Counter({4: 3, 2: 2, 3: 2, 1: 1, 7: 1, 8: 1, 45: 1})
[1, 2, 2, 3, 1, 1, 1]
[1, 2, 3, 4, 7, 8, 45]

Python collections - deque

Deque is another powerful data structure from collections. It implements all feature of Double-ended_queue.Lets see an example how to use it.


All source code available on github

from collections import deque

dq = deque([1,2,3])
print dq

dq.append(4) # add end of the deque
dq.appendleft(5) # add beginning of the deque

print dq

print dq.pop()
print dq.popleft()
print dq

dq.extend([22,33,44]) # add multiple element to end of existing deque
dq.extendleft([444,333]) # add multiple element to beginning of existing deque
print dq

print 22 in dq # search in deque

dq.rotate(1)
print "Right rotate:",dq
dq.rotate(-1)
print "Left rotate:",dq

Output:
deque([1, 2, 3])
deque([5, 1, 2, 3, 4])
4
5
deque([1, 2, 3])
deque([333, 444, 1, 2, 3, 22, 33, 44])
True
Right rotate: deque([44, 333, 444, 1, 2, 3, 22, 33])
Left rotate: deque([333, 444, 1, 2, 3, 22, 33, 44])

Python collections - OrderedDict

OrderDict remembers its insertion order. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.


All source code available on github

from collections import OrderedDict
d = OrderedDict()

d[3]=5
d[1]=6
d[20]=9
d["cse"]=77

print d

del d[1]
d[1] = 123

print d
print d[1]
print d["cse"]

Output:
OrderedDict([(3, 5), (1, 6), (20, 9), ('cse', 77)])
OrderedDict([(3, 5), (20, 9), ('cse', 77), (1, 123)])
123
77

Python collections - namedtuple

collections.namedtuple is a factory function for creating tuple subclasses with named fields. It can be used as struct or data container.

All source code available on github

from collections import namedtuple

Point = namedtuple('Point', ['x' ,'y'])

p1=Point(1, 2)
p2=Point(6, 4)

print p1
print p2
print "p1[0]",p1[0],"p1[1]",p1[1]
print "p2.x",p2.x,"p2.y",p2.y

Output:
Point(x=1, y=2)
Point(x=6, y=4)
p1[0] 1 p1[1] 2
p2.x 6 p2.y 4