问题
i have 3 Lists, for example:
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];
and i expect the common elements:
// [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.
thanks for helping.
回答1:
One solution :
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);
}
Result :
[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);
}
Result :
(7, 99, 21)
回答2:
You don't need nested loops or recursion for this. Dart has Sets and a very nice fold method on Lists.
main() {
final lists = [
[1, 2, 3, 55, 7, 99, 21],
[1, 4, 7, 65, 99, 20, 21],
[0, 2, 6, 7, 21, 99, 26]
];
final commonElements =
lists.fold<Set>(
lists.first.toSet(),
(a, b) => a.intersection(b.toSet()));
print(commonElements);
}
Gives:
{7, 99, 21}
Further, this can be used no matter how many lists are contained in lists.
回答3:
In case, if you want to use 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];
List result = [];
for (final e1 in l1) {
for (final e2 in l2) {
for (final e3 in l3) {
if (e1 == e2 && e1 == e3) {
result.add(e1);
}
}
}
}
print(result);
}
来源:https://stackoverflow.com/questions/59431806/extract-common-elements-from-lists-in-dart