如何计算列表中项目的出现次数
问题描述:
我是 Dart 的新手.目前我有一个重复项目列表,我想计算它们的出现次数并将其存储在 Map 中.
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"];
我希望得到如下结果:
{
"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!