4
votes

I have the following tuple.I want to build a string which outputs as stated in output.I want count all the elements corresponding to 'a' i.e, how many k1 occured w.r.t 'a' and so on .What is the easiest way to do this

a=[('a','k1'),('b','k2'),('a','k2'),('a','k1'),('b','k2'),('a','k1'),('b','k2'),('c','k3'),('c','k4')]

Output should be in a string output=""

 a k1  3
 a k2  1
 b k1  1
 b k2  3
 c k3  1
 c k4  1
2

2 Answers

2
votes

You can do the addition portion easily with defaultdict. The default dict works like a normal dictionary, except it has a default value for empty key stores so you can easily increment your counter when you iterate over your data set.

a=[('a','k1'),('b','k2'),('a','k2'),('a','k1'),('b','k2'),('a','k1'),('b','k2'),('c','k3'),('c','k4')]
from collections import defaultdict
b = defaultdict(int)
for item in a:
    b[item] += 1

print b
defaultdict(<type 'int'>, {('a', 'k2'): 1, ('c', 'k3'): 1, ('b', 'k2'): 3, ('a', 'k1'): 3, ('c', 'k4'): 1})

And for pretty printing it, just iterate over the resulting data and print it how you want.

for key, value in b.iteritems():
    print '%s %s %s' % (key[0], key[1], value)
6
votes

Use the Counter class from collections:

>>> a = [('a', 'k1'), ('b', 'k2'), ('a', 'k2'), ('a', 'k1'), ('b', 'k2'), ('a', 'k1'), ('b', 'k2'), ('c', 'k3'), ('c', 'k4')]
>>> from collections import Counter
>>> c = Counter(a)
Counter({('b', 'k2'): 3, ('a', 'k1'): 3, ('a', 'k2'): 1, ('c', 'k3'): 1, ('c', 'k4'): 1})

You can use c.items() to iterate over the counts:

>>> for item in c.items():
...     print(item)
... 
(('a', 'k2'), 1)
(('c', 'k3'), 1)
(('b', 'k2'), 3)
(('a', 'k1'), 3)
(('c', 'k4'), 1)

The above code is Python 3. The Counter class is new in Python 2.7. You can now rearrange the items in the desired order and convert them to a string if needed.