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)]
Use a Counter
like so:
>>> from collections import Counter
>>> l1=[2,2,2,5,5,7]
>>> c = Counter(l1)
>>> c.items()
dict_items([(2, 3), (5, 2), (7, 1)])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.