计算列表中的唯一元素 [英] Counting unique elements in a list

查看:30
本文介绍了计算列表中的唯一元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有标准高阶函数的直接组合来计算列表中的唯一元素?

Is there a straight-forward combination of standard higher-order functions to count the unique elements in a list?

例如结果

[1, 1, 4, 0, 4, 4]

应该是这样的

[(1,2), (4,3), (0,1)]

推荐答案

如果顺序不重要,这有效:

If order is not important this works:

map (xs@(x:_) -> (x, length xs)) . group . sort

<代码>组.sort 会给你一个列表列表,其中所有彼此相等的元素被分组到同一个子列表中(没有排序,只有连续的相等元素会被分组在一起).map 然后将每个子列表转换为 (element, lengthOfSublist)-tuple.

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.

如果你想按第一次出现对结果进行排序,你可以在排序前使用zip为每个元素添加一个索引,然后,在分组后,再次按该索引排序,然后删除索引.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆