我需要在列表中找到元素的频率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]如何计算列表中元素的频率?
3 回答
料青山看我应如是
TA贡献1772条经验 获得超8个赞
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]
慕田峪4524236
TA贡献1875条经验 获得超5个赞
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)]
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]>>> d = {x:a.count(x) for x in a}>>> d{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}>>> a, b = d.keys(), d.values()>>> a[1, 2, 3, 4, 5]>>> b[4, 4, 2, 1, 2]
添加回答
举报
0/150
提交
取消