如何计算列表中项目的出现 [英] How to count items' occurence in a List
本文介绍了如何计算列表中项目的出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Dart的新手.目前,我有一个重复项列表,我想计算它们的出现并将其存储在地图中.
I am new to Dart. Currently I have a List of duplicate items, and I would like to count the occurence of them and store it in a Map.
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
我想要一个类似这样的结果
I want to have a result like:
{
"a": 3,
"b": 2,
"c": 2,
"d": 2,
"e": 2,
"f": 1,
"g": 1,
"h": 3
}
我做了一些研究,发现了一个JavaScript解决方案,但我不知道如何将其翻译为Dart.
I did some research and found a JavaScript solution, but I don't know how to translate it to Dart.
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
推荐答案
试试看:
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
var map = Map();
elements.forEach((element) {
if(!map.containsKey(element)) {
map[element] = 1;
} else {
map[element] +=1;
}
});
print(map);
这是什么:
- 遍历列表元素
- 如果您的地图没有将列表元素设置为键,则创建一个值为1的元素
- 否则,如果元素已经存在,则在现有键值上加1
或者,如果您喜欢语法糖和一种衬板,请尝试以下一种:
Or if you like syntactic sugar and one liners try this one:
var elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e"];
var map = Map();
elements.forEach((x) => map[x] = !map.containsKey(x) ? (1) : (map[x] + 1));
print(map);
有许多方法可以在所有编程语言中实现!
There are many ways to achieve this in all programming languages!
这篇关于如何计算列表中项目的出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文