如何计算无序列表中元素的频率? [英] How to count the frequency of the elements in an unordered list?
本文介绍了如何计算无序列表中元素的频率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要找到无序列表中元素的频率
I need to find the frequency of elements in an unordered list
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
output->
b = [4,4,2,1,2]
我也想从a
a = [1,2,3,4,5]
推荐答案
注意:在使用 groupby
之前,应先对列表进行排序。
Note: You should sort the list before using groupby
.
如果列表是有序列表,则可以使用 itertools
包中的 groupby
。
You can use groupby
from itertools
package if the list is an ordered list.
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]
这篇关于如何计算无序列表中元素的频率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文