2016-05-31 41 views

回答

4

为此,您可以使用列表中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)] 
+2

Counter(l1).items()就够了;-) –

+0

刚发现,编辑! :) – Will

3

使用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)]) 
相关问题