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)]
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With