繁体   English   中英

如何将基于频率的列表中的元素分组为元组

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

我正在尝试将相似的数字组合成一个形式的元组(数字,频率)。

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()

“key”是列表元素,“value”是出现次数。

例如:

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

>>> from collections import Counter
>>> l1=[2,2,2,5,5,7]
>>> c = Counter(l1)
>>> c.items()
dict_items([(2, 3), (5, 2), (7, 1)])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM