Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python tuple operations and count

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
like image 325
Rajeev Avatar asked Feb 20 '23 00:02

Rajeev


1 Answers

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.

like image 142
Simeon Visser Avatar answered Feb 25 '23 16:02

Simeon Visser