我需要找到列表中元素的频率
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
输出->
->
b = [4,4,2,1,2]
我也想从中删除重复项
a = [1,2,3,4,5]
由于列表是有序的,你可以执行以下操作:
a = [1,1,1,1,2,2,2,2,3,3,4,5,5] from itertools import groupby [len(list(group)) for key, group in groupby(a)]
输出:
[4, 4, 2, 1, 2]
在Python 2.7(或更高版本)中,你可以使用collections.Counter:
collections.Counter
import collections a = [1,1,1,1,2,2,2,2,3,3,4,5,5] counter=collections.Counter(a) print(counter) # Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1}) print(counter.values()) # [4, 4, 2, 1, 2] print(counter.keys()) # [1, 2, 3, 4, 5] print(counter.most_common(3)) # [(1, 4), (2, 4), (3, 2)]
如果你使用的是Python 2.6或更早版本,则可以在此处下载。