Python tuple operations and counting

I have the following tuple. I want to build a string that is output as indicated in output.I want to count all the elements corresponding to "a", that is, how much k1 came from "a", etc. 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')] 

The output should be in the line output = ""

  a k1 3 a k2 1 b k1 1 b k2 3 c k3 1 c k4 1 
+4
source share
2 answers

Add a part with ease with defaultdict . By default, dict works like a regular dictionary, except that it has a default value for empty key stores, so you can easily increment the counter when you iterate over your dataset.

 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 in order to print it, just iterate over the received data and print it the way you want.

 for key, value in b.iteritems(): print '%s %s %s' % (key[0], key[1], value) 
+2
source

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 repeat the samples:

 >>> 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. Now you can arrange the elements in the desired order and convert them to a string, if necessary.

+5
source

All Articles