从dart列表中提取常见元素 [英] extract common elements from lists in dart
本文介绍了从dart列表中提取常见元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有3个列表,例如:
List l1 = [1, 2, 3, 55, 7, 99, 21];
List l2 = [1, 4, 7, 65, 99, 20, 21];
List l3 = [0, 2, 6, 7, 21, 99, 26];
我希望有共同的要素:
// [7,99,21]
这是我尝试过但无法正常工作的内容:
here is what i've tried but didn't work correctly:
List l1 = [1, 2, 3, 55, 7, 99, 21];
List l2 = [1, 4, 7, 65, 99, 20, 21];
List l3 = [0, 2, 6, 7, 21, 99, 26];
List common = l1;
l2.forEach((element) {
l3.forEach((element2) {
if (!common.contains(element) || !common.contains(element2)) {
common.remove(element);
common.remove(element2);
}
});
});
print(common);
另外,列表的数量是动态的,所以我希望像这样嵌套它们,我没有递归的经验,所以我做不到,甚至不知道它是否比嵌套循环好.
plus, the number of lists is dynamic, so i expect to nest them like this, i have no experience with recursion so i couldn't do it or even know if it's better than nesting loops.
感谢您的帮助.
推荐答案
一种解决方案:
void main() {
List l1 = [1, 2, 3, 55, 7, 99, 21];
List l2 = [1, 4, 7, 65, 99, 20, 21];
List l3 = [0, 2, 6, 7, 21, 99, 26];
l1.removeWhere((item) => !l2.contains(item));
l1.removeWhere((item) => !l3.contains(item));
print(l1);
}
结果:
[7,99,21]
[7, 99, 21]
如果列表的数量是动态的,那么一种解决方案是对所有列表中的所有出现次数进行计数,并且仅保留出现次数等于列表数量的值:
If your number of lists is dynamic, then a solution is to count all occurences within all the lists, and retains only values where number of occurence is equals to the number of lists :
void main() {
List<List> lists = [
[1, 2, 3, 55, 7, 99, 21],
[1, 4, 7, 65, 99, 20, 21],
[0, 2, 6, 7, 21, 99, 26]
];
Map map = Map();
for (List l in lists) {
l.forEach((item) => map[item] = map.containsKey(item) ? (map[item] + 1) : 1);
}
var commonValues = map.keys.where((key) => map[key] == lists.length);
print(commonValues);
}
结果:
(7,99,21)
(7, 99, 21)
这篇关于从dart列表中提取常见元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文