簡體   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