Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to group elements in a list based on frequency into a tuple

I'm trying to group the similar numbers into one tuple of the form (number,frequency).

l1=[2,2,2,5,5,7]

How do I convert this list into the list below

l1=[(2,3),(5,2),(7,1)]
like image 333
zaolee_dragon Avatar asked May 31 '16 20:05

zaolee_dragon


1 Answers

You can do this using Counter():

from collections import Counter

l1 = [2, 2, 2, 5, 5, 7]

l1 = Counter(l1).items()

The "key" is the list element, and the "value" is the occurrence count.

For example:

In [7]: from collections import Counter

In [8]: l1=[2,2,2,5,5,7]

In [9]: Counter(l1).keys()
Out[9]: [2, 5, 7]

In [10]: Counter(l1).values()
Out[10]: [3, 2, 1]

In [11]: zip(Counter(l1).keys(), Counter(l1).values())
Out[11]: [(2, 3), (5, 2), (7, 1)]

In [12]: Counter(l1).items()
Out[12]: [(2, 3), (5, 2), (7, 1)]
like image 68
Will Avatar answered Sep 23 '22 13:09

Will