我越来越喜欢 dart 的列表操作功能。然而,我经常发现自己需要“分区”函数,其中列表根据布尔标准分为两部分。含义与 相同.where,但不会丢弃错误的。
明显的实现:
Iterable partition(Iterable list, filter) {
var matches = [];
var nonMatches = [];
list.forEach((e) {
if (filter(e)) {
matches.add(e);
} else {
nonMatches.add(e);
}
});
return [matches, nonMatches];
}
Run Code Online (Sandbox Code Playgroud)
然而,我也越来越喜欢where正在返回的惰性迭代。
另一种实现是使用集合:
Iterable partition(Iterable list, filter) {
var matches = list.where(filter);
var nonMatches = list.toSet().difference(matches.toSet()).toList();
return [matches, nonMatches];
}
Run Code Online (Sandbox Code Playgroud)
我很高兴看到如何完成优雅的惰性实现(如果很容易的话)。我相信从列表构建集合是一种O(n)操作,因此两种实现在效率上不应有太大差异。希望对此发表评论。
更新
该集的实现是有缺陷的。我不明白为什么它不起作用,但 不nonMatches包含 中未包含的所有数字matches。
怎么样:
Iterable partition(Iterable list, filter) {
return [list.where((e) => filter(e)), list.where((e) => !filter(e))];
}
Run Code Online (Sandbox Code Playgroud)
问候罗伯特
| 归档时间: |
|
| 查看次数: |
498 次 |
| 最近记录: |