计算列表中的独特元素 [英] Counting unique elements in a list
问题描述
是否有一个标准高阶函数的简单组合来计算列表中的独特元素?
b$ b
[1,4,0,4,4]
可能类似于
[(1,2),(4,3 ),(0,1)]
map(\xs @(x:_) - >(x,length xs)) 。组。 sort
组。 sort
会给你一个列表,其中所有相互相等的元素被分组到相同的子列表中(没有排序,只有连续的相等元素将被分组在一起)。然后 map
将每个子列表转换为(element,lengthOfSublist)
-tuple。
如果您想要在第一次出现时对结果进行排序,您可以在排序之前使用 zip
将索引添加到每个元素,然后在分组,再按该索引排序,然后删除索引。
Is there a straight-forward combination of standard higher-order functions to count the unique elements in a list?
For example the result for
[1, 1, 4, 0, 4, 4]
would be something like
[(1,2), (4,3), (0,1)]
If order is not important this works:
map (\xs@(x:_) -> (x, length xs)) . group . sort
group . sort
will give you a list of lists where all elements that are equal to each other are grouped into the same sublist (without sort, only consecutive equal elements would be grouped together). The map
then turns each sublist into a (element, lengthOfSublist)
-tuple.
If you want to order the result by first occurrence, you can use zip
before the sort to add an index to each element, then, after grouping, sort again by that index and then remove the index.
这篇关于计算列表中的独特元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!