我试图将相似的数字分组到表单(数字,频率)的一个元组中。如何将基于频率的列表中的元素分组为一个元组
l1=[2,2,2,5,5,7]
如何转换这个名单到下面
l1=[(2,3),(5,2),(7,1)]
我试图将相似的数字分组到表单(数字,频率)的一个元组中。如何将基于频率的列表中的元素分组为一个元组
l1=[2,2,2,5,5,7]
如何转换这个名单到下面
l1=[(2,3),(5,2),(7,1)]
为此,您可以使用列表中Counter()
:
from collections import Counter
l1 = [2, 2, 2, 5, 5, 7]
l1 = Counter(l1).items()
“密钥” 是列表元素,而“值“是发生次数。
例如:
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)]
Counter(l1).items()就够了;-) –
刚发现,编辑! :) – Will
使用Counter
像这样:
>>> from collections import Counter
>>> l1=[2,2,2,5,5,7]
>>> c = Counter(l1)
>>> c.items()
dict_items([(2, 3), (5, 2), (7, 1)])
[使用计数器](https://docs.python.org/2/library/collections.html# counter-objects) – Hamms